[Python-Dev] Floating point -> string conversions

Brett C. bac at OCF.Berkeley.EDU
Fri Nov 12 22:28:13 CET 2004


Batista, Facundo wrote:
> There's a thread in the standard list (with this very Subject) that 
> talks about implicit coercing with "%d" in strings replacement.
> 
> jfouhy posted this example:
> 
>  >>> pow(2, 31)
> 2147483648L
>  >>> '%d' % 2147483647.0              # python will convert to int
> '2147483647'
>  >>> '%d' % 2147483648.0              # too big for an int, so error.
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: int argument required
>  >>> '%d' % long(2147483648.0)        # but yet, no trouble accepting a 
> long.
> '2147483648'
>  >>> '%d' % int(2147483648.0)         # and int() converts to long anyway
> '2147483648'
> 
> 
> I think that here's a bug, but don't know where:
> 

I say it is in the conversion from float not trying it as a long to make it 
work.  I expect the conversion types in string interpolation to convert the 
argument as needed to meet the conversion type.  Since a float can safely be 
converted to a long that is what should be done since in the eyes of Python int 
== long.

Just think of how printf() handles it; it just interprets the argument as what 
the conversion type says it is.  I think Python should do the same.

-Brett


More information about the Python-Dev mailing list