Who told str() to round my int()'s!!!

A.T.Hofkamp hat at se-162.se.wtb.tue.nl
Wed Aug 15 08:43:30 EDT 2007


On 2007-08-11, Adam W. <AWasilenko at gmail.com> wrote:
> After a fair amount of troubleshooting of why my lists were coming
> back a handful of digits short, and the last digit rounded off, I
> determined the str() function was to blame:
>
>>>> foonum
> 0.0071299720384678782
>>>> str(foonum)
> '0.00712997203847'
>>>>
>
> Why in the world does str() have any business rounding my numbers, and
> how do I get around this?

You have got a few good reactions already. What is not mentioned yet however is
the difference between str() and repr().


Python has two ways to stringify an object:

str() is intended to deliver a 'human-readable' representation of its argument,
and typically, humans think a few digits of a float is enough.

The repr() on the other hand is intended to deliver a 'machine-reproducible'
string representation of its argument, ie after "y = eval(repr(x))" y == x
should hold.

Note that no rounding occurs with the floating point number, arguments of both
str() and repr() are not changed.


So, depending on your intentions of str(foonum), you should either explicitly
format your floating point number yourself (ie if you want a more precise
human-readable representation of the number), or you should use repr() (if you
intend to use the string representation for reproducing the same object
elsewhere by a machine).


Albert



More information about the Python-list mailing list