(update)
Here's the actual problem I'm seeing. Note that round() doesn't seem to be doing the trick.
Here's my code:
t0=time.time()
# stuff
t1=time.time()
perfdat={'et1' : round(t1-t0,6), 'et2': '%.6f'%(t1-t0)}
And the dict and json output, respectively:
{'et2': '0.010214', 'et1': 0.010214000000000001}
{"et2":"0.010214","et1":0.010214000000000001}
(end update)
I've got a floating point value that has a lot of extra digits of precision that I don't need. Is there a way to truncate those digits when formatting a json string?
I can get the truncation I need if I format the value as a string, but I would like to transmit the value as a (truncated) number.
import json
v=2.030000002
json.dumps({'x':v}) # would like to just have 2.030
'{"x": 2.030000002}'
s= '%.3f' % (v) # like this, but not as a string
json.dumps({'x' : s})
'{"x": "2.030"}'
Python Decimal default precision The Decimal has a default precision of 28 places, while the float has 18 places.
Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming.
Float() in python is an important method that is useful to represent floating-point numbers. It is used to represent real numbers and is written with the decimals dividing the integer and fractional parts.
Format float value using the round() Method in Python The round() is a built-in Python method that returns the floating-point number rounded off to the given digits after the decimal point. You can use the round() method to format the float value.
Wrap the number into a float
:
>>> s = float('%.3f' % (v))
>>> json.dumps({'x' : s})
{"x": 2.03}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With