This question already has answers here:
Why I cannot the get percentage by using Int
(9 answers)
Closed 6 years ago.
When I enter, in the Windows Calculator utility, "15036/18218*100=" it returns 82.53375782193435
What I really want is 17.47 (100 - 82.53), but that's beside the point at the moment.
With this code:
// Example: thisQty == 3182; totalQty == 18218
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff/totalQty)*100; // this equates to 0.0 for some reason
return string.Format("{0}%", prcntg);
}
...I'm getting 0.0 for the prcntg value. Why? ISTM that this is the same operation that I'm doing by hand in the Calculator utility. Why doesn't it return 82.53375782193435?
The dividing of 2 ints will be an int even if the correct mathematical answer is with a fraction.
In order to have it keep the decimal part you must divide with a number of a type that holds the fraction part (like double or decimal):
Console.WriteLine(GetPercentage(3182, 18218));
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff / (double)totalQty) * 100;
return string.Format("{0}%", prcntg);
}
BTW - it doesn't matter if you cast to double the diff or the totalQty - for both it will do the / operation returning a double - which means keeping the fraction part
You are using an integer value, (which doesn't store factional part), so cast it to double, or use the parameter type as double (my recommendation). Your operation, 15036/18218 resolves to, 0.82 and in an integer value that is stored as 0... Where finally 0 * 100 is going to resolve to 0 anyways and that is where you get the result.
Try this instead,
private string GetPercentage(double thisQty, double totalQty)
{
double diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff/totalQty) * 100.0; // this equates to 0.0 for some reason
return string.Format("{0}%", prcntg);
}
This would have the fractional part too and you will get the result.
Based on Gilad Green's answer, here is what I ended up with, which gives the value I ultimately want, and also rounds the value to an integer:
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty;
double prcntg = (diff / (double)totalQty) * 100;
prcntg = 100 - prcntg;
int roundedPercent = Convert.ToInt32(prcntg);
return string.Format("{0}%", roundedPercent);
}
Related
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;
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;
This question already has answers here:
Why do these division equations result in zero?
(10 answers)
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 4 years ago.
I'm calculating the percentage to add in a datagrid, but when I report the data it always returns me 0, what am I doing wrong?
if I have the following case: the variable quantidadeInstalada has the value of 10 and the goal has 20 the concluido would have to return me 50 but it returns me 0
private void AdicionarPessoa()
{
string Valida = ValidaPessoa();
if (Valida.Equals(""))
{
double concluido=0, falta=0;
int quantidadeInstalada = Convert.ToInt32(ttbQuantidade.Text);
int meta = Convert.ToInt32(ttbMetaPessoa.Text);
concluido = (quantidadeInstalada/meta)*100;
falta = 100-concluido;
MessageBox.Show(concluido.Text);
}
else
MessageBox.Show(Valida);
}
It's probably due to the precision of the int. Use a decimal or double instead.
When we use an integer, we lose precision.
Console.WriteLine(100 / 17); // 5
Console.WriteLine(100 / 17m); // 5.8823529411764705882352941176
Console.WriteLine(100 / 17d); // 5.88235294117647
Console.WriteLine(100 / 17f); // 5.882353
Since integers always round down, 0.99 as an integer is 0.
Note that for precision, the types of the inputs matters.
double output = input1 * input2;
For example:
double outputA = 9 / 10;
Console.WriteLine(outputA); // 0
double outputB = 9 / 10d;
Console.WriteLine(outputB); // 0.9
double outputC = 9d / 10;
Console.WriteLine(outputC); // 0.9
Here is a Fiddle.
It's because you're doing integer division. You can fix it by casting one of the variables to a double like this:
concluido = ((double)quantidadeInstalada/meta)*100;
When you're dividing int by int (as in "quantidadeInstalada/meta"), you'll get an int. Either use a fractional type (e.g. decimal, double) from the very beginning, as Shaun suggested, or (if the integral types have to stay), cast the values to a fractional type in the division expression (as itsme86 shown).
This question already has answers here:
C# is rounding down divisions by itself
(10 answers)
C# double not working as expected [duplicate]
(1 answer)
Closed 7 years ago.
I have c# program that calculates percentage and returns int value, but it always returns 0.
I have been writing code for 16 constitutive hours so I appreciate if you find the mistakes within it.
I debugged my code and I found that the value is being passed correctly.
private int returnFlag(int carCapacity, int subscribers)
{
int percentage = (subscribers / carCapacity)*100;
return percentage;
}
What you're seeing is the result of operating on two integers, and losing the fractional portion.
This piece of code, when using the values 5 and 14, will truncate to 0:
(subscribers / carCapacity)
You need to cast one of the operands to a double or decimal:
private int returnFlag(int carCapacity, int subscribers)
{
decimal percentage = ((decimal)subscribers / carCapacity) * 100;
return (int)percentage;
}
The issue is that since you're performing math on int (read: integer) values, any fractions or remainders get thrown out. This can be seen by changing your code to
int percentage = (subscribers / carCapacity);
percentage *= 100;
Since (subscribers / carCapacity) results in less than one, the only possible number an int can hold is 0 - and 0 * 100 is 0.
You can fix this by converting to a more precise number, such as double, before performing operations:
private int returnFlag(int carCapacity, int subscribers)
{
double percentage = ((double)subscribers / (double)carCapacity) * 100.0;
return (int)percentage;
}
Integer types (int) don't work with fractions. Change the types you are working with in your division to decimal, double, single, or float.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)
how to return decimal with long rest after the point like that:
3.786444499963
to this:
3.787
its not just cut the points it also round the rest of the number
Math.Ceiling(3.786444499963 * 1000) / 1000;
But the generally accepted rounding of 3.786444499963 to three decimal places is 3.786. Why do you think otherwise?
Thus:
var round = Math.Round(3.786444499963m, 3, MidpointRounding.AwayFromZero);
Console.WriteLine(round == 3.786m); // prints true
If you want it to ALWAYS round up:
var round = Math.Round(3.786444499963m + 0.0005m, 3);
Console.WriteLine(round == 3.787m); // prints true
Do you see what I did there? I added 0.0005m to the input before using Math.Round. In general, to round x to n decimal places,
var round = Math.Round(x + 5m * Convert.ToDecimal(Math.Pow(10, -n - 1)), n);
Or, perhaps, to avoid the ugly double/decimal conversion:
int k = 1;
decimal value = 5m;
while(k <= n + 1) { value /= 10m; k++; }
var round = Math.Round(x + value, n);
There's an edge case you need to be aware of. What happens to 3.786? Should it be rounded up to 3.787 or remain at 3.786? You haven't specified what you want exactly, so I'll leave this edge case to you.
RoundUp(3.786444499963M, 3);
static decimal RoundUp(decimal dec, int precision)
{
decimal rounder = (decimal)(0.5 * Math.Pow(10, -precision));
return Math.Round(dec + rounder, precision);
}