This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: String format operator '%i' fails for large floats
Type: Stage:
Components: Interpreter Core Versions: Python 3.0, Python 2.6, Python 2.5
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: Nosy List: ctl, gvanrossum, mark.dickinson
Priority: low Keywords:

Created on 2008-01-01 02:38 by ctl, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg59068 - (view) Author: Christopher Tur Lesniewski-Laas (ctl) Date: 2008-01-01 02:38
To reproduce:
>>> '%i' % 12345678901.0
TypeError: int argument required

Contrast with:
>>> '%i' % 1234567890.0
'1234567890'

Previous experience led me to expect that the '%i' format code would
work for all numerical types.  Admittedly, there's nothing in the docs
promising this, but it works *almost* all the time.

In fact, the operator fails to convert floats which are too big to fit
into a machine long.  The code for the '%i' operator handles objects of
type long specially, and then uses PyInt_AsLong to handle all other
objects (in formatint).

The ideal solution would be to ask the object to convert itself into an
int *before* the special test for type long; this would give the
expected behavior.

An acceptable solution would be to make the behavior consistent by
refusing all floats passed as the argument to '%i', but I expect this
would break a lot of code.  Of course, right now most of that code is
broken anyway, since it will throw a TypeError when the input float
happens to be large.
msg59069 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2008-01-01 03:02
On the one hand, if you want to format a float like that, you should use
"%.0f".  On the other hand, this should either consistently fail or
succeed, not depending on how large the float is.

I think in 2.6 we can't change this, but in 3.0, I propose that all
these accept only integers.  I find the behavior of %x and %o with
floats particularly anti-intuitive.

On the third hand, we're expecting % to be phased out in favor of
.format(), which allows floats of any value with the i, d, o, x format
specifiers.  So perhaps we should leave this alone?
msg75836 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2008-11-13 20:49
> I think in 2.6 we can't change this,

I'm not sure when it happened, but it looks like this
*was* fixed for 2.6.

Closing.
History
Date User Action Args
2022-04-11 14:56:29adminsetgithub: 46057
2008-11-13 20:49:51mark.dickinsonsetstatus: open -> closed
nosy: + mark.dickinson
resolution: fixed
messages: + msg75836
2008-01-01 03:02:58gvanrossumsetpriority: low
nosy: + gvanrossum
messages: + msg59069
2008-01-01 02:38:29ctlcreate