3

I am using quite old Python 2.6.6 on Debian 6 (32-bit). Faced issue that any number with decimal 1 after dot represented like: 37.100000000000001 instead of 37.1. Ok, I'd like to return it as in was introduced, i.e. 37.1 as float in JSON response. And I want in returned as float (otherwise '{0}'.format(number) saves me).

UPD: sample taked on my system:

Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = 37.1
>>> f
37.100000000000001
>>> round(f,2)
37.100000000000001

When JSON prepared it looks like:

>>> import json
>>> f = 37.1
>>> json.dumps({'value': f})
{ 'value': 37.100000000000001 }

But I want it be:

{ 'value': 37.1 }
Alex G.P.
  • 9,609
  • 6
  • 46
  • 81
  • What? Are you talking about the result of `json.dumps`? Or something else? Could you give a [mcve]? – jonrsharpe Aug 13 '15 at 09:43
  • 1
    1/10th can never be exactly represented in a floating point number, regardless of the bit-size. – Martijn Pieters Aug 13 '15 at 09:43
  • @jonrsharpe updated post with required code sample – Alex G.P. Aug 13 '15 at 09:46
  • @MartijnPieters yes, I know. Question as how to send it to resulting JSON with desired form. – Alex G.P. Aug 13 '15 at 09:47
  • So what are you trying to use that number for? Why is its `repr` particularly important? If you want to *"send it to resulting JSON"*, why aren't you using `json`? – jonrsharpe Aug 13 '15 at 09:47
  • @jonrsharpe Hope it is more understandable with last update – Alex G.P. Aug 13 '15 at 09:50
  • Perhaps `round(f*100) / 100.0` could help as a workaround. – MC93 Aug 13 '15 at 09:54
  • 1
    @MC93 well, not really, the problem is (in short) that you can't represent all of the infinite real numbers with a finite number of bits, so some are necessarily approximations. This is just the abstraction leaking. – jonrsharpe Aug 13 '15 at 09:57
  • 1
    @AlexG.P.: JSON float numbers are still float numbers, it doesn't matter one bit if you include more precision in the string representation of the number. – Martijn Pieters Aug 13 '15 at 10:04
  • @MartijnPieters it is not my wish to manually handle 1/10th, but I cannot explain it to customer who is argued that he passed 37.1 and he want it returns back. – Alex G.P. Aug 13 '15 at 10:07

0 Answers0