26 lines
822 B
Python
26 lines
822 B
Python
|
#!/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
|
||
|
|