How to enable floating point number like 293.4662543 in 293.47 in python?

How to reduce the result of the float that I received? I need only 2 digits after the dot. Sorry, I really don't know how to explain this better in English ...

thanks

+7
python number-formatting
source share
7 answers

From the Python floating point manual 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, because float are binary fractions that cannot represent decimal digits exactly.

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

+24
source share

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

 >>> round(12.3456, 2) 12.35 

(but +1 for Michael responds to the Decimal type.)

If you need a line:

 >>> print "%.2f" % 12.34567 12.35 
+13
source share

From: Python docs round (x [, n]) Return a 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 nearest multiple of 10 to power minus n; if two multiples are equally close, rounding is performed 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 may be unexpected: for example, round (2.675, 2) gives 2.67 instead of the expected 2.68. This is not a mistake: it is the result of the fact that most decimal fractions cannot be represented exactly as floats. See Floating-Point Arithmetic: Problems and Limitations for more information.

It seems that round (293.466 .... [, 2]) will do it,

+5
source share
 >>> print "%.2f" % 293.44612345 293.45 
+2
source share

x = round(293.4662543, 2)

+2
source share

If you need numbers, for example, 2.3k or 12M, this function performs the task:

 def get_shortened_integer(number_to_shorten): """ Takes integer and returns a formatted string """ trailing_zeros = floor(log10(abs(number_to_shorten))) if trailing_zeros < 3: # Ignore everything below 1000 return trailing_zeros elif 3 <= trailing_zeros <= 5: # Truncate thousands, eg 1.3k return str(round(number_to_shorten/(10**3), 1)) + 'k' elif 6 <= trailing_zeros <= 8: # Truncate millions like 3.2M return str(round(number_to_shorten/(10**6), 1)) + 'M' else: raise ValueError('Values larger or equal to a billion not supported') 

Results:

 >>> get_shortened_integer(2300) 2.3k # <-- str >>> get_shortened_integer(1300000) 1.3M # <-- str 
0
source share

Hope this helps.

 def do(*args): formattedList = [float("{:.2f}".format(num)) for num in args] _result =(sum(formattedList)) result = round(_result,2) return result print(do(23.2332,45.24567,67,54.27)) 

Result:

 189.75 
0
source share

All Articles