我需要将十进制值999999.99990000005
编码为JSON格式,同时不失去精度,也不改变其表示方式为字符串。期望得到的结果是{ "prc" : 999999.99990000005 }
从[这篇帖子][1]中,我找到了以下代码。
import json
import decimal
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return str(o)
return super(DecimalEncoder, self).default(o)
y = { 'prc' : decimal.Decimal('999999.99990000005')}
但它会生成一个字符串。
json.dumps(y, cls=DecimalEncoder)
'{"cPrc": "999999.99990000005"}'
在
isinstance
中用float(o)
替换str(o)
会截断数字。
有没有办法得到非字符串结果?
附注:我不能使用任何外部模块,如simplejson。编辑: 如果我将值保留为字符串,则以下内容也会生成字符串。
>>> x = json.loads("""{ "cPrc" : "999999.99990000005" }""", parse_float=decimal.Decimal)
>>> x
{'cPrc': '999999.99990000005'}