2

Python's decimal.Decimal automatically converts the following number (7 zeros and a one, after the decimal point) into scientific notation:

d = decimal.Decimal('0.00000001')
import simplejson; simplejson.dumps({"val": d})
'{"val": 1E-8}' #what do I do so the output is '{"val": 0.00000001}' (float, not string)?

How could I change this so that the JSON output is 0.00000001 instead of 1E-8?

I cannot use solutions that employ format since it changes the type to string, but I need to preserve to type to decimal (or at least float).

Some context: The output is sent as JSON response of an API, and the client expects floats in decimal notation. Converting it to scientific notation OR changing the type to string breaks the contract with client.

rubayeet
  • 9,269
  • 8
  • 46
  • 55
  • After snooping around the net for a bit and testing in my console, it would appear this is not trivial. It is probably easier to convince the client to run a regex script to catch these outliers.. :( – Uvar Nov 30 '17 at 15:35
  • 2
    I am confused. Print() yields a _string_, no matter what, representing the object. Sometimes the string is '0.01', other times '1e-2', but the actual thing you see *is a string*. You're just formatting said string in a different way - hence you would use print "{}".format(). – jkm Nov 30 '17 at 15:49
  • @jkm - perhaps print was a poor example. Edited my question to show the real use case. – rubayeet Nov 30 '17 at 15:56
  • Since you're already using simplejson… how about `use_decimal=True`…? – deceze Nov 30 '17 at 15:58
  • @deceze could you provide an example? I tried some variations and could not get what I need. – rubayeet Nov 30 '17 at 16:02
  • Have you tried it as shown in the manual (https://simplejson.readthedocs.io/en/latest/), and you still get scientific notation…? – deceze Nov 30 '17 at 16:05
  • It seems `use_decimal` instructs the encoder to use `decimal.Decimal` instead of floats and has nothing to do with notations. – rubayeet Nov 30 '17 at 16:11
  • OK, fair enough, it doesn't seem to change scientific notation. But it does keep it as a float, which parses right back to the same decimal value. The fact that it doesn't look like you prefer should make absolutely no difference, since a valid JSON parser will parse it into the correct value. – deceze Nov 30 '17 at 16:14
  • It seems the only solution is to pass the buck to the client and ask them to use a JSON parser that recognises scientific notations. BTW, `simplejson.dumps` keeps it as float even if I don't use `use_decimal`. I'll close the question. – rubayeet Nov 30 '17 at 16:25

0 Answers0