Home c# Rounding rules
Reply: 2

c# Rounding rules

biscuitcleaver
1#
biscuitcleaver Published in 2018-01-12 15:16:11Z

This question already has an answer here:

  • Why does System.MidpointRounding.AwayFromZero not round up in this instance? 5 answers

I am running into a weird instance in C#(.net) where I believe the rounding is incorrect in the framework.

Math.Round(9.995, 2, MidpointRounding.AwayFromZero)

When I round this value, I get back 9.99. With the MidpointRounding.AwayFromZero set to this logic, my assumption is that it would round up to 10. Case in point:

Math.Round(9.95, 1, MidpointRounding.AwayFromZero)

Rounds to 10. It seems these results are inconsistent, but can anyone explain why or what I can do to help ensure proper rounding is applied?

Thanks!

BMS
2#
BMS Reply to 2018-01-12 15:20:21Z

Logical rounding: 5 -> 10

Programming's rounding: 5 -> 0

Adassko
3#
Adassko Reply to 2018-01-12 15:31:52Z

This is all about working on floating point numbers and its precision

9.95 is in fact represented as 9.949999885559079 and the result is as close to 10 as it might get after cummulating floating point accuracy errors

https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems

If you want a precise value, use decimal

Math.Round(9.995m, 2, MidpointRounding.AwayFromZero); // 10

You should also never compare floating numbers using "==" operator but check if it's "close enough". See this thread: Floating point comparison functions for C#

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.492422 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO