'Dividing large number by 10 in python gives the wrong result [duplicate]
Say I want to remove the last digit of a number n.
For that I use the code int(n/10).
Sadly this gives the wrong result for large numbers.
For example n = 4474630975855204960 divided by 10 gives 447463097585520512.
What's the reason for this behavior? How can I fix it?
Solution 1:[1]
For some math operations, the Python interpreter will handle long integers for you and you don't have to think about it.
Division is different and converts integers to floats, which aren't handled well in Python.
You can get around this by directly using integer division - two // rather than just one /.
Input
4474630975855204960//10
Output
447463097585520496
Solution 2:[2]
This syntax varies across python versions, use // to get integer division
$ python2 -c 'print("%d" % (4474630975855204960/10))' # Integer division
447463097585520496
$ python3 -c 'print("%d" % (4474630975855204960/10))' # Float division
447463097585520512
$ python3 -c 'print("%d" % (4474630975855204960//10))' # True division
447463097585520496
Solution 3:[3]
You can convert from int to str, remove the last character, and convert it back to an int:
n = 4474630975855204960
print(int(str(n)[:-1]))
Output:
447463097585520496
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ryan Ward |
| Solution 2 | Cireo |
| Solution 3 | Ann Zen |
