2

How to use python (3.5) json standard library to print floats with trailing zeros?

import json
to_be_serialized = {'something': 0.020}
print(json.dumps(to_be_serialized))
{"something": 0.02}  # desired output: {"something": 0.020}

I tried this but unfortunately without desired result.

Martin Brisiak
  • 3,872
  • 12
  • 37
  • 51

2 Answers2

1

Floats aren't designed to hold that kind of information. 0.020 and 0.02 are identical.

You can however manually set the number of decimals:

import json
test = 0.020
print(json.dumps({'test': '{:.3f}'.format(test)}))

will print

{"test": "0.020"}

Note that a) this is now a string and no longer a float and b) that the {:.3f} part specifically sets the number of decimals to three.

orangeInk
  • 1,360
  • 8
  • 16
1

In the end I was forced to use non-standard python library simplejson. (cause json package is not supporting decimals)

import simplejson as json
from decimal import Decimal

to_be_serialized = {'something': Decimal('0.020').quantize(Decimal('.0001'))}
print(json.dumps(to_be_serialized))

I was unable to find a way to do this with standard json library, but at least it's working.

Martin Brisiak
  • 3,872
  • 12
  • 37
  • 51