How does Rounding in Python work?

I'm a bit confused about how rounding works in Python.
Can anyone explain why Python is behaving this way?

Example:

>>> round(0.05,1) # this makes sense 0.1 >>> round(0.15,1) # this doesn't make sense! Why is the result not 0.2? 0.1 

And the same for:

 >>> round(0.25,1) # this makes sense 0.3 >>> round(0.35,1) # in my opinion, should be 0.4 but evaluates to 0.3 0.3 

Edit: In general, it is likely that Python is rounded rather than rounded. So I have to understand that the only "abnormal" thing that can happen is that Python is rounded up? Or can it also round up โ€œabnormallyโ€ because of how it is stored? (I did not find a case where Python was rounded, when I expected it to round)

+5
source share
3 answers

It is actually by design. From the Pythons documentation:

The behavior of round() for floats may be unexpected: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a mistake : it is the result of the fact that most decimal fractions cannot be represented exactly as floats.

+12
source

It seems to me that you need a decimal module:

 from decimal import * x = Decimal('0.15') print x.quantize(Decimal('0.1'), rounding=ROUND_HALF_UP) 

Output:

 0.2 
+7
source

As an example, here you can round:

 >>> round(0.0499999999999999999,1) 0.1 

In this case, 17 "9" is the minimum number causing this behavior. This is because the internal view is 0.0499999999999999999 0.05000000000000000277555756156289135105907917022705078125 .

+3
source

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


All Articles