Python JSON serialize a Decimal object

后端 未结 17 1164
星月不相逢
星月不相逢 2020-11-22 08:27

I have a Decimal(\'3.9\') as part of an object, and wish to encode this to a JSON string which should look like {\'x\': 3.9}. I don\'t care about p

17条回答
  •  隐瞒了意图╮
    2020-11-22 09:15

    3.9 can not be exactly represented in IEEE floats, it will always come as 3.8999999999999999, e.g. try print repr(3.9), you can read more about it here:

    http://en.wikipedia.org/wiki/Floating_point
    http://docs.sun.com/source/806-3568/ncg_goldberg.html

    So if you don't want float, only option you have to send it as string, and to allow automatic conversion of decimal objects to JSON, do something like this:

    import decimal
    from django.utils import simplejson
    
    def json_encode_decimal(obj):
        if isinstance(obj, decimal.Decimal):
            return str(obj)
        raise TypeError(repr(obj) + " is not JSON serializable")
    
    d = decimal.Decimal('3.5')
    print simplejson.dumps([d], default=json_encode_decimal)
    

提交回复
热议问题