I have the following code:
int a = Convert.ToInt32(4.5m);
int b = Convert.ToInt32(5.5m);
Console.WriteLine(a);
Console.WriteLine(b);
And here's the output:
4
6
Why does Convert.ToInt32
rounds decimal values to the nearest even number?
Convert is using rounding to nearest, or banker's rounding:
The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.
To control the type of rounding used by the Round method, call the Math.Round(Double, MidpointRounding) overload.
int a = (int)Math.Floor(4.5m);
int b = (int)Math.Floor(5.5m);
MSDN:
Or:
int a = decimal.ToInt32(4.5m);
int b = decimal.ToInt32(4.5m)
You can also just use the explicit int cast operator:
int a = (int) 4.5m;
int b = (int) 5.5m;
But read this note from MSDN:
This operator supports the explicit conversion of a Decimal to a Int32. The syntax for such explicit conversions is language-dependent, and individual language compilers can provide different implementations and return different results. The example illustrates the different return values when you explicitly convert a Decimal value to an Int32 value by using C# and Visual Basic. To perform a conversion that is independent of language, you can call the ToInt32 or the Convert.ToInt32(Decimal) method.
Math.Floor Method (Decimal)
Returns the largest integer less than or equal to the specified decimal number.
Note that decimal is bigger than int
so if the value is bigger than int.MaxValue
you get an OverflowException
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With