How to turn a float number like 293.4662543 into 293.47 in python?

Shane picture Shane · Oct 12, 2010 · Viewed 79.1k times · Source

How to shorten the float result I got? I only need 2 digits after the dot. Sorry I really don't know how to explain this better in English...

Thanks

Answer

Michael Borgwardt picture Michael Borgwardt · Oct 12, 2010

From The Floating-Point Guide's Python cheat sheet:

"%.2f" % 1.2399 # returns "1.24"
"%.3f" % 1.2399 # returns "1.240"
"%.2f" % 1.2 # returns "1.20"

Using round() is the wrong thing to do, because floats are binary fractions which cannot represent decimal digits accurately.

If you need to do calculations with decimal digits, use the Decimal type in the decimal module.