You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

25 lines
822 B

#!/usr/bin/env python
## from https://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module
class PrettyFloat(float):
def __repr__(self):
return '%.15g' % self
def pretty_floats(obj):
if isinstance(obj, float):
return PrettyFloat(obj)
elif isinstance(obj, dict):
return dict((k, pretty_floats(v)) for k, v in obj.items())
elif isinstance(obj, (list, tuple)):
return map(pretty_floats, obj)
return obj
def rounded_floats(obj, ndigits=15):
if isinstance(obj, float):
return PrettyFloat(round(obj, ndigits))
elif isinstance(obj, dict):
return dict((k, rounded_floats(v, ndigits)) for k, v in obj.items())
elif isinstance(obj, (list, tuple)):
return map(lambda o: rounded_floats(o, ndigits), obj)
return obj