3

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?

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Amal Rajan
  • 153
  • 1
  • 11

2 Answers2

7

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
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • The variable ```a``` is already defined with the value mentioned in the question. The code already contains a line ```a = 999999999999999.99```. In your code, you are declaring the value of ```a``` inside the ```decimal.Decimal()```. So basically, I need to get the value from ```a``` and then print it. – Amal Rajan Feb 14 '17 at 20:29
  • The value I'm passing to `decimal.Decimal` is not the same as the value assigned to `a` in the question. My value is a string literal. This is necessary to preserve the precision. If you do `a = decimal.Decimal(999999999999999.99)`, then `a` will be `Decimal('1000000000000000')` instead. – Kevin Feb 14 '17 at 20:31
  • How do I convert it into a string an then use ```decimal.Decimal(string)```? ```a``` is already declared as float type. – Amal Rajan Feb 14 '17 at 20:33
  • 1
    If `a` is already a float, then you have permanently lost the precision and there's no way to get it back. – Kevin Feb 14 '17 at 20:34
4

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.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299