C # Rounding Rules

I got confused in a weird instance in C # (. Net) where, in my opinion, rounding in the structure is wrong.

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

When I round this value, I will return to 9.99. Given that MidpointRounding.AwayFromZero is tuned to this logic, my assumption is that it will be rounded to 10. Example:

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

Rounds to 10. These results seem to be inconsistent, but can anyone explain why or what I can do to ensure proper rounding?

Thank!

+4
source share
3 answers

It's all about working on floating point numbers and precision

9.95 is actually represented as 9.949999885559079, and the result is close to 10, because it can get after errors with floating point errors

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

, decimal

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

"==", , " ". . : #

+4

9.95 9.995 double , , .NET , - 10, ( ). , 64- IEEE 754 :

> 9.95 * 10
99.5
> 9.995 * 100
999.4999999999999

-! . decimal .

+1

Logical rounding: 5 → 10

Rounding programming: 5 → 0

-5
source

Source: https://habr.com/ru/post/1692102/


All Articles