Jesvin Jose
Jesvin Jose

Reputation: 23088

Is json.dumps guaranteed not to lose floating point precision?

I am talking of a JSON conversion like:

>>> a = {'asas': 1/7.0}
>>> b = json.dumps(a)
>>> c = json.loads(b)
>>> c
{u'asas': 0.14285714285714285}
>>> c['asas'] == 1.0/7
True

Is the JSON encoding guaranteed not to roundoff the number?

In my How to store a floating point number as text without losing precision?, Mark Dickinson says that repr doesnt cause loss of precision. Does json.dumps use the repr?

Upvotes: 7

Views: 1950

Answers (1)

Fred Foo
Fred Foo

Reputation: 363607

There is no mention of repr anywhere in the json docs, but it is the current implementation of float-to-string coercion:

FLOAT_REPR = repr

(Lib/json/encoder.py, line 31)

You can build your own JSONEncoder if you want a strict guarantee.

Upvotes: 8

Related Questions