0

I was just randomly trying out different float to string conversions, in which I found the following issue:

str(123456789.123456789)

which is returning

'123456789.12345679'

where the 8 is missing. Is this a memory issue or what might I be not understanding here?

KVSEA
  • 109
  • 8
  • Close dup of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – martineau Feb 20 '21 at 21:20

2 Answers2

2

Try typing the float that you used as an example directly in your Python console: you will see that it prints out as 123456789.12345679 instead of 123456789.123456789. This is simply a rounding issue.

Sheldon
  • 4,084
  • 3
  • 20
  • 41
2

The default floating-point formatting behavior in some Python implementations is now to produce just as many digits as needed to uniquely distinguish the number represented. In the floating-point format most commonly used, 123456789.123456789 is not exactly representable. When this numeral is encountered in source text, it is converted to the nearest representable value, 123456789.12345679104328155517578125.

Then, when that is formatted as a string, “123456789.12345679” is printed because fewer digits fail to distinguish it from nearby representable values, like 123456789.123456776142120361328125, and more digits are not necessary, as the “…79” suffices to distinguish it from its two neighbors “…77…” and “…80…”.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312