python json rpc loses precision when working with floating point. Patch included

250 views
Skip to first unread message

Robby

unread,
Jan 9, 2014, 10:23:38 AM1/9/14
to json...@googlegroups.com
With the current version of python json-rpc (available from http://json-rpc.org/wiki/python-json-rpc), the following fails:

from decimal import *
from jsonrpc import ServiceProxy, json
n = Decimal("50000000.00000008")
num = int(json.loads(json.dumps(float(n)))*1.0e8)
assert num == 5000000000000008

This fails because json.dumps() ends up stripping the specified float down. The fix is:

--- trunk/python-jsonrpc/jsonrpc/json.py 2014-01-09 10:19:38.321829000 -0500
+++ newtrunk/python-jsonrpc/jsonrpc/json.py 2014-01-09 10:13:12.568585718 -0500
@@ -114,8 +114,10 @@
             for part in dumpParts (item):
                 yield part
         yield u']'
-    elif objType in [IntType, LongType, FloatType]:
+    elif objType in [IntType, LongType]:
         yield unicode(obj)
+    elif objType in [FloatType,]:
+        yield unicode(repr(obj))
     else:
         raise JSONEncodeException(obj)

As repr will keep precision when converting from float, where straight unicode() will not always (non authoritative answer: http://stackoverflow.com/a/3481575)

Can we have this fixed in python-jsonrpc?

Matt (MPCM)

unread,
Jan 9, 2014, 10:54:13 AM1/9/14
to json...@googlegroups.com
I'll see about getting that patch in, if someone here more familiar with python can validate the change proposed.

While I currently host the sites, including the original trac site, that python implementation is not supported or actively maintained in any sense.

In fact, if this implementation isn't already on github, I'd suggest you fork it over to there, apply your fix. :)
Reply all
Reply to author
Forward
0 new messages