Skip to content

Instantly share code, notes, and snippets.

@iancoleman
Last active November 17, 2020 19:55
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iancoleman/4536693 to your computer and use it in GitHub Desktop.
Save iancoleman/4536693 to your computer and use it in GitHub Desktop.
Decimal numbers in python json dump
# In response to https://bitcointalk.org/index.php?topic=56424.msg1454348#msg1454348
# Highlights that json encoding of floats is no good
# and that decimals can be used for encoding.
import json
from decimal import Decimal as D
d1 = D(11) / D(10) # 1.1
d2 = D(22) / D(10) # 2.2
f1 = 1.1
f2 = 2.2
# See http://docs.python.org/2/library/json.html
# Extending JSONEncoder:
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, D):
return float(obj)
return json.JSONEncoder.default(self, obj)
print json.dumps({'a': f1+f2})
# {"a": 3.3000000000000003} # This is not what we want, should be 3.3 exactly
#print json.dumps({'a': d1+d2})
# Fails for json encoding of decimal
print DecimalEncoder().encode({'a': d1+d2})
# {"a": 3.3}
Copy link

ghost commented Nov 3, 2015

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment