Python – How to change the precision of a variable in Python

numeric precisionpython

I'm working on a 2D-physics engine, and I need a certain variable to be precise only to the hundredths. Are there any methods for basically shaving off all of that unneeded precision?

I have tried things like

"{0:.2f}".format(a)

but that obviously produces a string, not a number.

I'm moving an object based upon its speed, and I want it to(obviously) stop when its value is 0.0, but it keeps going because its speed is really something like 0.0000562351.

Best Answer

It is typical to compare floats using a tolerance, rather than by equality. This both avoids some of the issues with floating point arithmetic on computers and allows you to specify an appropriate level of precision. In your case, if you only care about hundredths of a unit:

if abs(speed - limit) < 0.01:
    ...

For example:

>>> abs(0.0 - 0.0000562351) < 0.01
True
Related Topic