Problems With Percentage [duplicate] - c#

This question already has answers here:
C# Bug or Something Wrong [duplicate]
(4 answers)
Closed 6 years ago.
I am developing an app for a client. It should get some inputs from the console, like total meal price; plus, the second line should ask for the tip percentage. The third would ask for taxPercent.
I have the following code, but it fails one of two test cases.
When I enter 15.50 for mealCoast, 15 percent for tip and 10% for tax, it passes the test case. However, if I enter 12.00 for mealCost, 20 for tip% and 8 for tax percent, it fails to meet the test case requirements.
Here you can see my code sample.
double mealCoast = double.Parse(Console.ReadLine());
int tipPercent = int.Parse(Console.ReadLine());
int taxPercent = int.Parse(Console.ReadLine());
//Calculating %
tipPercent = Convert.ToInt16(mealCoast) * (tipPercent) / 100;
taxPercent = Convert.ToInt16(mealCoast) * (taxPercent) / 100;
int totalCast = Convert.ToInt16(mealCoast) + tipPercent + taxPercent;
Console.WriteLine("The total meal cost is {0} dollars.", totalCast);
Console.ReadKey();

A couple of possible issues:
Firstly, beware of the integer division. It basically means that if you divide int data type by int data type, you will get int result. Note that you use int all over the places, which is not a good practice - in your application, likely you don't want that. But rather you want to be precise in your money-involved computation. Thus, I suggest to use double - or better - decimal for your data computation
Secondly, beware of the non-convertible string to the respective number data type (be it int or floating point like double). Don't use Parse, but use TryParse to ensure the input is convertible.
By using correct data type and correct way to process the data, you would already half-way accomplishing your goals. Putting them into code, this is how it may look like:
decimal mealCoast, tipPercent, taxPercent; //use decimal, probably is best
bool mealCoastResult = decimal.TryParse(Console.ReadLine(), out mealCoast);
bool tipPercentResult = decimal.TryParse(Console.ReadLine(), out tipPercent); //use TryParse
bool taxPercentResult = decimal.TryParse(Console.ReadLine(), out taxPercent);
//Input checking, check any parsing error
if (!mealCoastResult || !tipPercentResult || !taxPercentResult){
//do some error handlers
return; //probably don't continue is good
}
//you could also put some while loop
//Calculating %
tipPercent = mealCoast * tipPercent / 100;
taxPercent = mealCoast * taxPercent / 100;
decimal grandTotal = mealCoast + tipPercent + taxPercent;
Console.WriteLine("The total meal cost is {0} dollars.", grandTotal);
Console.ReadKey();

however second case 12.00 for mealPrice , 20 for tip and 8 for tax fails to produce required output output should be 15 usd it prints 14 usd strange thing taxtPercent variable become 0
Let's have a look at your code for the example:
double mealCoast = double.Parse(Console.ReadLine()); // mealCoast = 12.
int tipPercent = int.Parse(Console.ReadLine()); // tipPercent = 20
int taxPercent = int.Parse(Console.ReadLine()); // taxPercent = 8
//Calculating %
// Convert.ToInt16(mealCoast) will give you 12
// you are using integer division here, no digits preserved after period.
tipPercent = Convert.ToInt16(mealCoast) * (tipPercent) / 100; // 12 * 20 / 100 = 2
taxPercent = Convert.ToInt16(mealCoast) * (taxPercent) / 100; // 12 * 8 / 100 = 0
// 12 + 2 + 0 = 14
int totalCast = Convert.ToInt16(mealCoast) + tipPercent + taxPercent; // 14
Console.WriteLine("The total meal cost is {0} dollars.", totalCast);
Console.ReadKey();
/ operator is integer division if its operands are of integer types. It will truncate all the decimal digits after period. This also does not depend on the type of the variable you are assigning result at. Take a look at decimal or double data types.

Related

changing celsius to fahrenheit and vice versa in c# [duplicate]

This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;

Lamda expression not working on String.Count() [duplicate]

This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;

basic maths calculations in c# [duplicate]

This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;

C# Round up and down

I'm counting the results of my database.
If it's lower then 50, i want to divide them by 2.
Example:
if(CountResults < 50)
{
//CountResults = 39
int divided = CountResults / 2; //Results in 19
}
What i want:
if(CountResults < 50)
{
//CountResults = 39
int divided = CountResults / 2; //Results in 19,5
Math.Round(divided, 0);
}
I want to be able to round it upwards and down.
So i get the result 19.5 twice. Once i want it to be 19, and once to be 20..
How do i achieve this?
It's not clear how you are going to use your code twice, but if you want to divide integer into two integer parts just subtract first result from totals:
if(CountResults < 50)
{
//CountResults = 39
int divided1 = CountResults / 2; // 19
int divided2 = CountResults - divided1; // 20
}
First result will use integer division and it will give you result rounded towards zero (19 in your case). Further reading: C# Specification 7.7.2 Division Operator
Second result will give you rest which will be either equal to first result (if there was no rounding), or it will be equal to division rounded from zero (20 in your case).
The rounding part can be accomplished using these 2 nice methods:
Math.Floor brings it to the floor
Math.Celing lifts it to the celing ;)
The calculation part is a little more tricky. This statement:
int divided = CountResults / 2; //Results in 19,5
cannot really be true, or let's say it does not matter what is behind the comma because when it is assigned to the variable int devided it will loose this information and no rounding is anymore required.
When you want a result of type double (meaning e.g. 19,5 ) and you want to round that result, you need at least one of the parameters of the calculation to be of type double double!
Example
double var1 = 39;
int res_low = (int)Math.Floor(var1 / 2);
int res_high = (int)Math.Ceiling(var1 / 2);
note that writing 2 is implicitly seen by the compiler as int and writing 2.0 is implicitly seen as double. So this would yield the same result:
int var2 = 39;
int res_low2 = (int)Math.Floor(var2 / 2.0);
int res_high2 = (int)Math.Ceiling(var2 / 2.0);

Working percentage in c#

I have two values one with a decimal value
and another value with a value which will calculate the percentage of that decimal value
for example:
60 % of 10 = 6
decimal value1 = 10;
decimal percentage = 60;
textbox1.text = ("mathsum here").toString();
How would you calculate this value using the decimal value and value containing the percentage value?
number * percentage / 100
so
10 * 60 / 100 = 6
Maybe it will help you to think of it in this way.
6
-- = .6 (or equivalent to your 60%)
10
In your example you'd like to know how to calculate the numerator (the 6) so assign a variable to it. Let's use X.
X
-- = .6
10
.. and solve for X by multiplying both sides by 10 (in your case).
X * 10 = .6 * 10
------
10
X = .6 * 10
From this I hope you can see that you can take your percentage value and multiply it by your 'decimal' value.
Note that in order to get the .6 you will need to convert your percentage (60) by dividing it by 100.
So our final formula is:
60
--- * 10
100
or using your variables:
percentage
---------- * value1
100
I hope I've added to your understanding even if my formula is similar to the previous answers. I wanted to make sure you understood how the formula was derived.
Good luck!
var result = (percentage/100) * value1;
textbox1.Text = result.ToString();
You mean like this?
textbox1.text = (value1 * percentage/100).ToString();
By the way, toString is written ToString in C# with a capital T.
var answer = value1 * (percentage/100);
Wouldn't this just be
percentage/100m*value
?
To get the percentage amount
decimal Value = 1200;
int percentage = 20; //20%
var result=(percentage/100)*(Value);
I would separate the concerns:
Calculate a portion of your original decimal:
decimal result = (value * percentage) / 100.0;
Provide an appropriate formatter to output the result as a percentage:
text = result.ToString("0.0%");
http://www.dotnetperls.com/percentage
You need to divide by 100.
60% = 60/100.
from question it self answer is clear
60% means 60/100 then calculate it with the value
60 / 100 * 10 = 6 use the logic for variables
textbox1.Text = ((percentage /100) * value).ToString();
or
textbox1.Text = ((percentage * .01 ) * value).ToString();

Categories