Mahdi
Mahdi

Reputation: 1035

How to avoid rounding float numbers in python?

I have some json objects and when I convert them into dictionary in python they will rounded:

-112.07393329999999  ->  -112.0739333

My code is:

for line in open("c:\\myfile","r+").readlines():          
     d = json.loads(line)
     logtv = d['logtv']

Upvotes: 1

Views: 3338

Answers (2)

cmd
cmd

Reputation: 5830

The answer is don't use floats. In most languages floats only have about 6 digits of significance and not too many more for doubles (note python floats are doubles). Use decimals if you know the exact precision. For JSON send it as a string or an int with an implied decimal point.

soap box: floats are very much overused. Floats should not be used by anything that you wouldn't represent with scientific notation, as that is what they really are underneath.

Note: Databases do not usually use floating point numbers, they use fixed point numbers. Which is exactly what a decimal is.

clarification

before you write the json file do something like

with  open("c:\\myfile","w") as my_file:
    for key in d:
        if isinstance(d[key], Decimal):
            d[key] = str(d[key])
    my_file.write(json.dumps(d))

then when reading the json, you can just put the value into the database as is or convert it back to Decimal if you need to work with it more.

Upvotes: 3

Pavel Anossov
Pavel Anossov

Reputation: 62888

It's just a more compact representation of the same (binary, 64-bit) number.

In [12]: -112.07393329999999 == -112.0739333
Out[12]: True

In [17]: struct.pack('d', -112.0739333)
Out[17]: 've\xbcR\xbb\x04\\\xc0'

In [18]: struct.pack('d', -112.07393329999999)
Out[18]: 've\xbcR\xbb\x04\\\xc0'

If you want this exact decimal, there's no way to represent it as a number in JSON. You'll have to use strings in your JSON, Decimals/strings in your python and decimal fields in your DB.

 

SQL Server Floats are at most 64-bit (53-bit significand) as well.

Upvotes: 7

Related Questions