0

I have an issue with C# not calculating correctly for me to draw my progress bar.

int width = 130;
int maxValue = 20;
int value = 20;

int percent = (width / maxValue) * value

Now it should return 130 so it mean my progress bar is full but it returns 120 so I don't know what is happening.

here is and image of progress bar https://i.stack.imgur.com/JhYnX.jpg

I also tested the formula with VB.NET and it worked perfectly.

I am using VS2013 in Windows 7 x86.

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147

4 Answers4

3

130 / 20 performs integer divison

From / Operator (C# Reference)

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2

That's why it always discards the fractional part and it returns 6. That's why your result will be 6 * 20 which is equal to 120.

As a solution, you can change your integer division to floating-point division.

For example;

var percent = (130.0 / 20) * 20;
var percent = (130 / 20.0) * 20;

That means, you need to define one of your variable as a double, or cast one of them to double in your calculation.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

You need to cast the values to double:

int percent = (int)(((double)width / (double)maxValue) * (double)value);

130 / 20 = 6.5 and it will be implicitely converted to integer which makes 6 of it. So the wrong value is used for the following multiplication

Flat Eric
  • 7,971
  • 9
  • 36
  • 45
1

Since you're dividing two int variables, you're performing integer division. 130/20 is 6.5, which, in integer context is truncated to 6. It is then multiplied by 20, to generate the result of 120.

You could avoid this issue completely by defining your variables as doubles:

double width = 130;
double maxValue = 20;
double value = 20;

double percent = (width / maxValue) * value;
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

In most programming languages, dividing an integer by an integer always results in an integer.

If you don't want an integer result, make sure at least one of the operands is a float or double:

int width = 130;
float maxValue = 20.0;
int value = 20;

int percent = (width / maxValue) * value
Rik
  • 28,507
  • 14
  • 48
  • 67