2

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?

Red
  • 26,798
  • 7
  • 36
  • 58
Nico G.
  • 487
  • 5
  • 12

3 Answers3

7

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
Ryan Ward
  • 196
  • 1
  • 10
  • 1
    No language handles floats any better; they are a fixed-precision approximation of real numbers. – chepner Dec 23 '20 at 01:12
3

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
Cireo
  • 4,197
  • 1
  • 19
  • 24
1

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
Red
  • 26,798
  • 7
  • 36
  • 58