Amal Rajan
Amal Rajan

Reputation: 153

How to convert large float values to int?

I have a variable containing a large floating point number, say a = 999999999999999.99

When I type int(a) in the interpreter, it returns 1000000000000000. How do I get the output as 999999999999999 for long numbers like these?

Upvotes: 3

Views: 2608

Answers (2)

Kevin
Kevin

Reputation: 76254

999999999999999.99 is a number that can't be precisely represented in the floating-point format, so Python compromises and picks the closest value that can be represented. In this case, that happens to be 1000000000000000. That's why converting that to an integer gives you 1000000000000000.

If you need more precision than floats can provide, consider using decimal.Decimal.

>>> import decimal
>>> a = decimal.Decimal("999999999999999.99")
>>> a
Decimal('999999999999999.99')
>>> int(a)
999999999999999

Upvotes: 7

Matteo Italia
Matteo Italia

Reputation: 126927

The problem is not int, the problem is the floating point value itself. Your value would need 17 digits of precision to be represented correctly, while double precision floating point values have between 15 and 16 digits of precision. So, when you input it, it is rounded to the nearest representable float value, which is 1000000000000000.0. When int is called it cannot do a thing - the precision is already lost.

If you need to represent this kind of values exactly you can use the decimal data type, keeping in mind that performance does suffer compared to regular floats.

Upvotes: 4

Related Questions