Python 3 with large integers

9.2k views Asked by At

I use Python to handle some large integers (64-bit, unsigned). I'm trying to convert a string of values to integers. However my Python3 gave me incorrect results. For example, if I convert an input string of "12736193479609682490" to integer, the result is not what I expected:

a = '12736193479609682490'
b = int(float(a))

>>>b
12736193479609681920

I'm usng Python 3.4.0 under ubuntu 12.04-64bit. What should I do to make a correct conversion? Thanks.

2

There are 2 answers

2
wim On BEST ANSWER

Don't convert to float first.

>>> int("12736193479609682490")
12736193479609682490

That number is too big to store in a float accurately!

0
Mark Ransom On

Don't convert to float first, that's where you're losing the accuracy.

b = int(a)

A float starts failing after it gets above 9007199254740992. Odd values at first, then more and more as it gets larger.