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: Obscure bug in the int() function
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ammar2, nathan snobelen
Priority: normal Keywords:

Created on 2016-08-05 21:57 by nathan snobelen, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg272062 - (view) Author: nathan snobelen (nathan snobelen) Date: 2016-08-05 21:57
Hi, I've noticed a bug in int() when converting a specific range of numbers it will incorrectly round the last digit down.

We have some payment code which formats numbers for processing in our system and we noticed that the payment of 1108431.38 was dropped by a penny to 1108431.37.  I looked into it and found that it is dropped when it is multiplied by 100 (to remove the decimal) and then converted back to an int.

Note, this bug only applies to the following range of numbers: 1108431.38 - 1108431.41.  Any other number I tried was unaffected. 

The following code will replicate the bug:

import math

amount1 = 110843138.0
amount2 = 1108431.38 * 100

print "Orig amount1 " + str(amount1)
print "Orig amount2 " + str(amount2)

print "Converted amount1 " + str(int(amount1))
print "Converted amount2 " + str(int(amount2))

Try it, and you will see that "amount1" remains correct, but "amount2" is affected.  Multiplying by 100 seems to trigger it... however note that even after it has been multiplied by 100 it is still correct... it's only when you then apply the int() function that the penny drops.

So it would appear that something is wrong in the int() function.

Cheers,
Nathan
msg272064 - (view) Author: Ammar Askar (ammar2) * (Python committer) Date: 2016-08-05 22:03
You've ran into a classic floating point number limitation. 
Please read the following doc page: https://docs.python.org/2/tutorial/floatingpoint.html

The problem comes when you multiply the number by 100, which is what causes the precision loss and drops it by a penny.

>>> 1108431.38 * 100
110843137.99999999
>>> int(110843137.99999999)
110843137

If this is for currency, I would suggest you use the decimal module https://docs.python.org/2/library/decimal.html
History
Date User Action Args
2022-04-11 14:58:34adminsetgithub: 71884
2016-08-05 22:08:42berker.peksagsetstatus: open -> closed
resolution: not a bug
stage: resolved
2016-08-05 22:03:24ammar2setnosy: + ammar2
messages: + msg272064
2016-08-05 21:57:18nathan snobelencreate