The problem of inaccurate calculation of python floating point number

calculation results do not meet expectations, such as

print (94 * .01)
result:
0.9400000000000001

Is there any way to avoid this problem automatically?
(the above problems can be solved with round (94 * .01,2), but is there a quasi-automatic method that can be calculated by default)

Aug.13,2021

Python is not the only problem.


this is not a python problem, but a floating-point error. This problem exists in the computer itself, and there are many explanations for search engines.
We need to make it clear that, even if this is not the case, the error must exist, especially when it comes to division, so we can only accept the error and control it within a reasonable range.

to avoid floating-point errors, you can avoid using floating-point numbers, such as representing floating-point numbers as fractions. Of course, I don't know if it really works, but at least it works here.

In [1]: 94*1/float(100)
Out[1]: 0.94

in fact, this idea is to convert all of them into integers and finally output them to floating-point numbers. The systems that are more sensitive to this are generally related to finance, and everyone's plans seem to be not much different.

Menu