str more precise in 3 as 2.7

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Apr 30 06:29:31 CEST 2015


On Wednesday 29 April 2015 21:24, Cecil Westerhof wrote:

> I am trying to make my modules also work under Python 3. I found that
> str is more precise in Python 3. The expression:
>     str(134 / 6.0)
> gives in 2.7.8:
>     '22.3333333333'
> and in 3.4.1:
>     '22.333333333333332'

The precise details of how floats are displayed may vary. In general, if you 
care about the exact details, you should control them by hand using either 
C-style % string interpolation, or the format method:


py> x = 134 / 6.0
py> "%.16f" % x
'22.3333333333333321'
py> "{:.16f}".format(x)
'22.3333333333333321'


-- 
Steve




More information about the Python-list mailing list