Reputation: 3760
I'm using Flask-Restless 0.17 for an API. The API has several fields that are decimals. I can successfully return decimals by installing simplejson as talked about here: https://stackoverflow.com/a/15224186/1753891.
However, when I have a decimal field that is 0, the value is in scientific notation such as 0E-8
. I would like to instead return 0.00000000
.
I'm trying something like this, but an unable to get it to work. The 0 is still returned in scientific notation.
class DecimalJSONEncoder(json.JSONEncoder):
# Try to format the decimal
# EDIT: but am now realizing that this doesn't work
# It was serializing the decimal at all because I had
# simplejson installed.
def default(self, o):
if isinstance(o, decimal.Decimal):
return format(str(o), '.8f')
return super(DecimalJSONEncoder, self).default(o)
def init_app(app):
# .....
# Use the Flask-Restless postprocessor to format.
def postprocesor(result, **kw):
json.dumps(result, cls=DecimalJSONEncoder)
How can I force decimals to be 0.00000000
when they are zeros?
Upvotes: 5
Views: 334