0

I came up with a formula to keep numbers a simple int and was surprised to see that the following was producing a 0.

var x = 45;
var y = 100;
var z = Convert.ToDecimal(x / y * 100);

In the above example, it almost seems ridicilous that I'm dividing by 100, then multiplying by 100 but in most cases, the x and y values are not nice integers.

When my x and y values end up being integers, the above conversion produces a 0. Why is that?

Sam
  • 26,817
  • 58
  • 206
  • 383

2 Answers2

2

X / Y = 0.45

Int conversion of 0.45 is 0.

Therefore 0 * 100 = 0.

Therefore Convert.ToDecimal(0) is 0.

Erez Shlomo
  • 2,124
  • 2
  • 14
  • 27
1

This does look a bit odd, but the problem there is with the order the expressions are evaluated: first the arguments of Convert are evaluated, and that is done inintegers. That’s why the result is truncated.

You should replace the conversation with an expression that forces evaluation in decimals:

var z = 100M * x / z;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523