views:

132

answers:

5

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

+1  A: 
>>> print "%.2f" % 293.44612345
293.45
ghostdog74
+5  A: 

From : Python Docs round(x[, n]) Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

Looks like round (293.466....[, 2]) would do it,

onaclov2000
Thanks! It's exactly what I'm looking for!
Shane
@Shane: no, it really isn't.
Michael Borgwardt
A: 

x = round(293.4662543, 2)

Ethan Shepherd
+2  A: 

If you want a number, use the round() function:

>>> round(12.3456, 2)
12.35

(but +1 for Michael's answer re. the Decimal type.)

If you want a string:

>>> print "%.2f" % 12.34567
12.35
RichieHindle
+8  A: 

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.

Michael Borgwardt
@Michael Borgwardt Supposing you need to store that result for future use, would something like x = "%.2f" work, or how do you still use that data, rather then simply printing it (as I have seen others below use the print function) EDIT: I should probably just follow your link, sorry. EDIT again, sorry still not sure how the original question I asked works with that syntax. +1 as your way looks good!
onaclov2000
@onaclov2000: as I wrote: if you need to work with decimal data, you should be using a decimal data type instead of float.
Michael Borgwardt