Fix Python – round() doesn’t seem to be rounding properly

Question

Asked By – swilliams

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?

Now we will see solution for issue: round() doesn’t seem to be rounding properly


Answer

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

'%.1f' % round(n, 1) # Gives you '5.6'

This question is answered By – Jimmy

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0