Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MidpointRounding in Math.Round not working correctly in C#

The MidpointRound.AwayFromZero overload is supposed to round the 5 up in a rounding situation.

EX: Math.Round(1.5, 1, MidpointRounding.AwayFromZero);

This rounds 1.5 to 2.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, when I try Math.Round(1.025, 2, MidpointRounding.AwayFromZero); it rounds it down to 1.02. It is supposed to round up to 1.03 though.

Does anyone have any idea why this is happening? Thanks!

>Solution :

The value 1.025 cannot be represented exactly as the type double. Floating point numbers have that problem. See Why are floating point numbers inaccurate?.

When you write 1.025 as a double number, it will internally be a little bit smaller than 1.025. That’s why the rounding delivers an unexpected value.

When dealing with money or other stuff where you want the value be exactly the same as displayed, use the type decimal instead of double:

decimal roundedValue = Math.Round(1.025m, 2, MidpointRounding.AwayFromZero);

Note that the m after the number turns the number into a literal of the decimal type.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading