0

I have a c# code which calculates (304/1000)*100, which equals 30.4, however when I run the code in c# every single time I get 0.

decimal width = (maxSize.Width/ maxValue) * value; //304, 1000, 100 respectively
Console.WriteLine(width); //Returns 0

I don't understand what the hell is going on?

vxern
  • 3
  • 3

3 Answers3

1

Your input variables are all of type int. Cast any of them into decimal or suffix the number with the letter M to convert to a decimal before the calculation is performed.

Pranav Negandhi
  • 1,594
  • 1
  • 8
  • 17
  • It doesn't change anything, I still get 0 as a result – vxern Nov 04 '18 at 17:53
  • 1
    @vxern, your problem is because of the integer division. Hence, you would need to cast one (or both) of the **division operands** to decimal, turning the division from an integer division into an decimal division. Casting the result of the division, or casting the multiplication operand to decimal won't help (as in that case you would then still be left with an integer dvision...) So, yeah, the answer here given is somewhat inaccurate when saying "_Cast any of them [...]_" –  Nov 04 '18 at 18:00
  • Absolutely correct. I overlooked the detail that there are multiple operators in the equation. My bad. – Pranav Negandhi Nov 04 '18 at 18:05
1

Use correct type

maxSize.Width = 304m;
maxValue = 1000m;
value=100m;

decimal width = (maxSize.Width/ maxValue) * value;
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
1

It seems as if you are using ints for the operands.

With int division, you must remember that the decimal part of the result gets truncated.

I.e., for the line (304/1000)*100 (replacing the variables with their values for simplicity), the following is calculated:

304 is divided by 1000, which results in 0.304. Then, the decimal is truncated, since this is integer division, resulting in 0 being the end result.

Then, 0 is multiplied by 100, which gives 0 as the result.

Solution:

Make the operands decimals, floats, or doubles. (100m, 100f, and 100d, respectively, for an example of each type)

These three types support decimals, so if you use them, you will get the correct result of 30.4.

Either that, or you can multiply one of the values in the parentheses by 1.0 of any of the three above types:

(1.0f * 304 / 1000) * 100

absoluteAquarian
  • 510
  • 3
  • 12