Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Convert decimal to int32

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?

like image 724
šljaker Avatar asked May 11 '12 10:05

šljaker


2 Answers

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.

like image 195
ie. Avatar answered Sep 18 '22 16:09

ie.


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

like image 37
gdoron is supporting Monica Avatar answered Sep 18 '22 16:09

gdoron is supporting Monica