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.
Related
This question already has answers here:
C# Maths gives wrong results!
(4 answers)
Closed 9 months ago.
Hi I have the function:
public static string MapDiePitchY(string DiePitchY)
{
float value = float.Parse(DiePitchY) * 1000;
int valInt = (int)value;
string temp = valInt.ToString();
return temp;
}
When I run it with these two numbers, I get two different behaviours:
str = MapDiePitchY("4150.8");
Returns 4150799
While
str = MapDiePitchY("2767.3");
Returns
2767300 which is what I'd expect and want everytime I pass in a float
I want the function to always return the value multiplied by 1000 but with no rounding. I've tried to replace the 1000 with 1000f and still get the behaviour where it adds extra value to 4150.8. Values that shouldn't exist there. I have no idea why this is happenign and googling hasn't given me any answers.
Is there a way to ensure I get the exact value I pass in as string but multiplied by 1000 with no rounding?
I am on C# 7.3
So you understand floating-point numbers are not exact. When you type float x = 4150.8f the internal bit representation of the number is
x = (1 + 112230 * 2^(-23)) * 2^(139-127) = 4150.7998046875
The integers m=112230 and e=139 represent the mantissa and exponent of the floating-point number.
The above is the result of the parse function. Then you multiply by 1000 which results in
value = x*1000 = 4150799.8046875
what you want to do at this point is do the rounding before converting into an integer
int valInt = (int)Math.Round(value);
which should round up the .80.. in the end into the next whole number 4150800.
This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 1 year ago.
I am trying to use a function in windows form application that convert a given point to another coordinate system. However, I encountered a strange problem. The input are correct but output is always 0. First, I thought it caused because of the local variables and then instead of variables I used only integers but it did not solve. I have no idea about it. Here the code and output basically:
string[] newPoint1 = convertPoints(X1, Y1);
string[] convertPoints(int oldX, int oldY)
{
//int newX = ((oldX - oldLeft) / (oldRight - oldLeft)) * (newRight - newLeft);
MessageBox.Show(oldX.ToString()); // output is 296
int newX = (oldX / 500) * 4096; // ????????????????????? (296/500) * 4096 = 0 ?????????????
MessageBox.Show(newX.ToString()); // here output is 0
int newY = newTop + ((oldY - oldTop) / (oldBottom - oldTop)) * (newBottom - newTop);
//MessageBox.Show(newY.ToString());
string[] newPoints = {newX.ToString(), newY.ToString()};
//MessageBox.Show(newPoints[0], newPoints[1]);
return newPoints;
}
This is working as it should. Because oldX is an Integer, when you divide it, it rounds (drops anything after the decimal). I would convert it to float and back into an integer, like so
int newX = (int)(((float)oldX / 500) * 4096);
This will preserve the whole number until you're done at the end. You'll also need to do the same for the Y values
An integer division cuts off the decimal places. So in your case, 296/500 you would expect 0.592. As integer has no decimal places, it cuts off them off resulting in 0.
Change the oldX to double and divide by 500.0
You are getting 0 because oldX/500 is a fraction usually and since you are using the int datatypes there can only be whole numbers. What I would recommend doing is changing the data type then rounding yourself.
//Old code
int newX = (1 / 500);
Console.WriteLine(newX);
// writes 0 to console
//New code
double newXD = (1 / 500.0) * 4096;
Console.WriteLine(newXD);
//Writes 8.192
The 1 and the 500 are considered ints try
Console.WriteLine(1/500);
It writes 0 to the console.
Console.WriteLine(1/500.0);
Console.WriteLine((float)1/500);
Console.WriteLine((double)1/500);
All these write 8.192 to the console.
Then after you have the double or other more accurate data type consider rounding if you really want an int.
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:
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);
}
This question already has answers here:
simple calculation not working for some reason
(4 answers)
Closed 8 years ago.
This is what I have on my C# code:
Int64 Free = Convert.ToInt64(number1); //has to be ToInt64
Int64 Size = Convert.ToInt64(number2); //has to be ToInt64
Int64 Total = (Free/Size) * 100;
Free is 35387133952 and Size is 64419262464
Manually dividing Free/Size I get 0.5493
PROBLEM: Instead of Total return 54.93 it is returning 0
Any ideas why this might be happening?
Thanks
You are trying to divide two integers. This is expected behavior.
If you need to get a floating point answer, you need to cast the values to floating point:
double Total = ((double)Free/(double)Size) * 100;
you are dividing ints so you get an int back.
If free and size need to be int64's you can convert them to floats or doubles ect like so..
double total = ((double)Free/(double)Size) * 100
but there is no way to store 54.93 into an int .. so Total cannot be an int