Also, be ready for some surprises if you use float or double (see other
posts on this ng). If you want predictable results for your rounding
operations, you should use the decimal type.
If you want to round half-up (or rather towards infinity, which means
rounding half-down on negative numbers), you can use the following:
static decimal RoundHalfTowardsInfinity(decimal dec) { return dec > 0 ?
(int)(dec + 0.5m) : (int)(dec - 0.5m); }
Side note for MS: it would be nice if the .NET framework provided rounding
methods for the various rounding modes, aka. Java's BigDecimal.
Bruno.
"Bruno Jouhier [MVP]" <bj******@club-internet.fr> a écrit dans le message de
news:%2****************@TK2MSFTNGP12.phx.gbl...
"Norvin Laudon" <no************@molinospamenergy.com> a écrit dans le
message de news:%2****************@TK2MSFTNGP09.phx.gbl... Hi,
Can somebody explain the following, from the MSDN documentation for the
"System.Convert.ToInt32(double)" function
<quote>
Return Value
value rounded to the nearest 32-bit signed integer. If value is halfway
between two whole numbers, the even number is returned; that is, 4.5 is
converted to 4, and 5.5 is converted to 6.
</quote>
Is there some obvious reason for this behaviour that I'm missing? Why would one want 4.5 to be rounded to 4 rather than 5?
And, why would one want 4.5 to be rounded to 5 rather than 4?
From a mathematical standpoint, 4.5 is halfway. So why would rounding it
up make sense and rounding it down not make sense?
Rounding always in the same direction increases the chances of getting
strong deviations when you add lots of numbers that have been rounded. The
banker's rounding rule tries to reduce this undesirable effect.
Bruno
Confused,
Norvin