# Gavin Andresen # 2011-03-03 15:26:16 # https://bitcointalk.org/index.php?topic=4086.msg58928#msg58928 genjix: here is how to do it right in Python2.6 : @p{par} Code: @p{brk} import decimal @p{brk} import json @p{par} # From @s{(link)} @p{brk} class DecimalEncoder(json.JSONEncoder): @p{brk} def _iterencode(self, o, markers=None): @p{brk} if isinstance(o, decimal.Decimal): @p{brk} return (str(o) for o in [o]) @p{brk} return super(DecimalEncoder, self)._iterencode(o, markers) @p{par} decimal.setcontext(decimal.Context(prec=8)) @p{par} print json.dumps(decimal.Decimal('10.001'), cls=DecimalEncoder) @p{brk} print json.dumps({ "decimal" : decimal.Decimal('1.1'), "float" : 1.1, "string" : "1.1" }, cls=DecimalEncoder) @p{brk} print json.loads('{"blaa": 0.333331}', parse_float=decimal.Decimal) @p{brk} Produces output: @p{brk} Code: 10.001 @p{brk} {"decimal": 1.1, "float": 1.1000000000000001, "string": "1.1"} @p{brk} {u'blaa': Decimal('0.333331')} @p{brk} @p{brk} Note that EVEN IF YOU PASSED THE 'WRONG' strings to Bitcoin, Bitcoin would do the right thing. That is, these two are equivalent once they are parsed by bitcoin: @p{brk} Code: sendtoaddress FOO 10.000999999999999 @p{brk} sendtoaddress FOO 10.001 @p{brk} ... because bitcoin does proper rounding. @p{par} On the bitcoin side, this is a non-issue. And if code on the other end of the JSON-RPC connection does the wrong thing (truncates values like 10.000999999999999 instead of rounding them to the nearest 8'th decimal place) then that's a bug in that code. @p{brk}