round() doesn't seem to be rounding properly
The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should do this:
n = 5.59
round(n, 1) # 5.6
But, in actuality, good old floating point weirdness creeps in and you get:
5.5999999999999996
For the purposes of UI, I need to display 5.6
. I poked around the Internet and found some documentation that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. See here also.
Short of creating my own round library, is there any way around this?
Solution 1:
I can't help the way it's stored, but at least formatting works correctly:
'%.1f' % round(n, 1) # Gives you '5.6'
Solution 2:
Formatting works correctly even without having to round:
"%.1f" % n
Solution 3:
If you use the Decimal module you can approximate without the use of the 'round' function. Here is what I've been using for rounding especially when writing monetary applications:
from decimal import Decimal, ROUND_UP
Decimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)
This will return a Decimal Number which is 16.20.
Solution 4:
round(5.59, 1)
is working fine. The problem is that 5.6 cannot be represented exactly in binary floating point.
>>> 5.6
5.5999999999999996
>>>
As Vinko says, you can use string formatting to do rounding for display.
Python has a module for decimal arithmetic if you need that.
Solution 5:
You get '5.6' if you do str(round(n, 1))
instead of just round(n, 1)
.