round() in Python doesn't seem to be rounding properly


Question

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?

1
113
6/4/2017 8:39:27 PM

Accepted Answer

I can't help the way it's stored, but at least formatting works correctly:

'%.1f' % round(n, 1) # Gives you '5.6'
97
10/19/2018 7:41:26 PM

Formatting works correctly even without having to round:

"%.1f" % n

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon