0

I'm trying to output a decimal number that is saved in a pandas series object.

The number is 7.45. But when I output it it becomes 7.449999809265137. I need it to be 7.45. How do I access the exact number 7.45 and not a floating point value that approximates 7.45?

---series_data['High'] Symbols PIH 7.45 TPNL 0.75 TURN 2.05 Name: 2018-01-02 00:00:00, dtype: float64

--- series_data['High']['PIH'] 7.449999809265137

user1144251
  • 327
  • 1
  • 3
  • 12
  • That's the number in your series. – juanpa.arrivillaga Feb 03 '19 at 19:14
  • but standard print ouputs 7.45 when i have it output the series though. not 7.449999809265137 – user1144251 Feb 03 '19 at 19:18
  • Yes, so? `pandas` objects do a lot of formatting. – juanpa.arrivillaga Feb 03 '19 at 19:19
  • The floating-point format(s) used by most Python implementations are binary based and cannot represent 7.45 exactly. There is no way to represent 7.45 in a binary floating-point type. Your choices are to using the binary floating-point type and round output to two decimal digits after the decimal point or to use another format to represent the number, such as a character string, a scaled integer, or the `decimal` module. – Eric Postpischil Feb 03 '19 at 19:24
  • Did you try `repr()`? – Darius Feb 03 '19 at 19:25
  • closely related to https://stackoverflow.com/questions/20457038/how-to-round-to-2-decimals-with-python. Just check this out and you should get the answer – Random Channel Feb 03 '19 at 19:30
  • tried repr(), didn't work. I"m forced to just format the output. But how does Series.toString() know how to output two decimal places? I have to use the following to get get the number showing properly: format(series_data['High']['PIH'],'.4f') – user1144251 Feb 03 '19 at 19:33

2 Answers2

0

As stated above, the number being held in memory is the number with many decimal places. You may have reached that number while expecting to see 7.45 due to some numerical precision issue. Representation of floating point numbers is not always exact. For example:

>>> 0.1 + 0.2
0.30000000000000004
>> 

You have a couple choices when you extract the number: you could format it to 2 decimal places (and retain the full representation in memory), you could forcibly round it off and change what is in memory:

x = numpy.round(x, 2)   # will round x to 2 decimal places and save that value
AirSquid
  • 10,214
  • 2
  • 7
  • 31
0

Floating points are not designed for precise values, but for measument data which inherently have a certain precision. Please read https://floating-point-gui.de/

For printing up to a certain precision use string formatting options like %2f % nr

Please don't round floating points

Mihai Andrei
  • 1,024
  • 8
  • 11