Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: forcing precision on a floating point number in json?

Tags:

python

json

(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"}'
like image 455
Mark Harrison Avatar asked Aug 21 '15 17:08

Mark Harrison


People also ask

How precise are floats in Python?

Python Decimal default precision The Decimal has a default precision of 28 places, while the float has 18 places.

How do you get high precision in Python?

Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming.

Can Python represent floating point numbers?

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.

How do you set floating points in Python?

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.


1 Answers

Wrap the number into a float:

>>> s = float('%.3f' % (v))
>>> json.dumps({'x' : s})
{"x": 2.03}
like image 78
l'L'l Avatar answered Oct 10 '22 16:10

l'L'l