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.

Title: Integer conversion inconsistent
Type: Stage:
Components: None Versions: Python 2.5
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: helminthe, loewis, rhettinger
Priority: normal Keywords:

Created on 2008-06-01 22:31 by helminthe, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (6)
msg67609 - (view) Author: Razvan Cosma (helminthe) Date: 2008-06-01 22:31
This issue is probably older than I am, and was amazed to discover it in
Python 2.5.2 (r252:60911, May  7 2008, 15:19:09)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
>>> int(float("-23.15"))
>>> int(float("-23.65"))
>>> int(float("24.9"))
>>> int(float("24.4"))
Is this by design? What is the python way of obtaining a correct result?
msg67612 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2008-06-01 22:41
I don't see any problem with that result? Why do you consider the result
incorrect, and what "correct" result would you have inspected instead?

Notice that int conversion of floats truncates them, by definition.
msg67613 - (view) Author: Razvan Cosma (helminthe) Date: 2008-06-01 22:44
As far as I know, the correct conversion is to either round to the
nearest, or to the smaller integer, but not both.
msg67614 - (view) Author: Razvan Cosma (helminthe) Date: 2008-06-01 22:45
Sorry for not writing completely above - python does neither, it rounds
to the integer closest to zero
msg67615 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2008-06-01 22:49
I see. There is no such thing as a "correct" conversion from real
numbers to integer numbers. Instead, there are various approaches,
called "truncating", "rounding", "flooring", and "ceiling". Python's
default conversion is truncation, and it is consistent in doing so:
int(x) will return the nearest integer between 0 and x.

If you want rounding, use the round builtin.
msg67616 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2008-06-01 22:51
This is exactly what int() is supposed to do.  For other kinds of 
rounding, look at round(), math.floor(), math.ceil(), and many rounding 
options in the decimal module:

from decimal import Decimal
>>> Decimal('-23.15').to_integral(ROUND_FLOOR)
>>> Decimal('-23.15').to_integral(ROUND_CEILING)
>>> Decimal('-23.15').to_integral(ROUND_DOWN)
>>> Decimal('-23.15').to_integral(ROUND_HALF_EVEN)
Date User Action Args
2022-04-11 14:56:35adminsetgithub: 47274
2008-06-01 22:51:35rhettingersetnosy: + rhettinger
messages: + msg67616
2008-06-01 22:49:54loewissetstatus: open -> closed
resolution: not a bug
messages: + msg67615
2008-06-01 22:45:56helminthesetmessages: + msg67614
2008-06-01 22:44:12helminthesetmessages: + msg67613
2008-06-01 22:41:08loewissetnosy: + loewis
messages: + msg67612
2008-06-01 22:31:17helminthecreate