.Net Rounding issue (MidpointRounding)

Issue:

.Net rounding does not work as you would expect. -2.5 rounds to -2 and not -3. What?! Yes! By default .Net uses MidpointRounding.ToEven which will round it to -2. BUT if you round off -3.5 it works as you would expect to -4. If you round off -6.5 you think it would also round off to -7, but you would be wrong, -6! What about 2.5, the default rounds off the 2 and not 3 as you would expect.

So what is going on? You can read more about it at http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx.

The fix below is to make sure it ALWAYS rounds off the same way.

Fix:

To make sure it consistently rounds off the same way, use the .Net enum MidpointRounding:

var amount = Math.Round(notRoundedDecimalValue, 0, MidpointRounding.AwayFromZero);

This will make sure -2.5, rounds to -3

Some other examples:

base           rounded to 0 decimals after comma

-1.5            -2 (same for both))

-2.5            -3 (default -2)

-3.5            -4 (same for both))

-4.5            -5 (default -4)

-5.5            -6 (same for both))

-6.5            -7 (default -6)

-7.5            -8 (same for both)

1.5            2 (same for both)

2.5            3 (default 2)

6.5            7 (default 6)

So to make sure it consistently rounds of the same way regardless of the number range you are in use:

MidpointRounding.AwayFromZero

Print | posted @ Tuesday, October 11, 2011 2:53 PM

Comments on this entry:

No comments posted yet.

Post A Comment
Title:
Name:
Email:
Comment:
Verification: