Python Typecasting Error – Fix ‘Typecasting to int Generating Wrong Result’

divisionintpythonpython-3.x

I tried performing following typecast operation in Python 3.3

int( 10**23 / 10 )

Output: 10000000000000000000000

And after increasing power by one or further

int( 10**24 / 10 )

Output: 99999999999999991611392

int( 10**25 / 10 )

Output: 999999999999999983222784

Why is this happening? Although a simple typecasting like

int( 10**24 )

Output: 1000000000000000000000000

is not affecting the values.

Best Answer

You are doing floating-point division with the / operator. 10**24/10 happens to have an inexact integer representation.

If you need an integer result, divide with //.

>>> type(10**24/10)
<class 'float'>
>>> type(10**24//10)
<class 'int'>
Related Question