repr/str diff between Python 2 and 3

Skip Montanaro skip.montanaro at gmail.com
Tue Oct 11 20:59:59 EDT 2016


I'm trying to port some code from Python 2 to 3, and beyond the usual
mechanical stuff, I've encountered a difference between the str() of
floats. Here's an example. In Python 3 I get:

>>> print(repr(27.04 - 0.01))
27.029999999999998
>>> print(str(27.04 - 0.01))
27.029999999999998

but in Python 2 str() behaves differently:

>>> print repr(27.04 - 0.01)
27.029999999999998
>>> print str(27.04 - 0.01)
27.03

My test case writes through a csv writer, which writes the str() of each
element to the output. My test assertions are looking at the output, not
the numeric input, so the option to test if the number is "close enough"
isn't readily available. I suppose I should adjust my test case, as in this
case 27.04-0.01 is different than 27.03.

Is there documentation of this particular change? My searching turned up
documentation of plenty of other changes, but not this particular one.

Thx,

Skip



More information about the Python-list mailing list