"%.2f" does not return a clean float. It returns a string representing this float with two decimals.
my_list = [0.30000000000000004, 0.5, 0.20000000000000001]
my_formatted_list = [ '%.2f' % elem for elem in my_list ]
returns:
['0.30', '0.50', '0.20']
Also, don't call your variable list. This is a reserved word for list creation. Use some other name, for example my_list.
If you want to obtain [0.30, 0.5, 0.20] (or at least the floats that are the closest possible), you can try this:
my_rounded_list = [ round(elem, 2) for elem in my_list ]
returns:
[0.29999999999999999, 0.5, 0.20000000000000001]
Answer from eumiro on Stack Overflow"%.2f" does not return a clean float. It returns a string representing this float with two decimals.
my_list = [0.30000000000000004, 0.5, 0.20000000000000001]
my_formatted_list = [ '%.2f' % elem for elem in my_list ]
returns:
['0.30', '0.50', '0.20']
Also, don't call your variable list. This is a reserved word for list creation. Use some other name, for example my_list.
If you want to obtain [0.30, 0.5, 0.20] (or at least the floats that are the closest possible), you can try this:
my_rounded_list = [ round(elem, 2) for elem in my_list ]
returns:
[0.29999999999999999, 0.5, 0.20000000000000001]
If you really want an iterator-free solution, you can use numpy and its array round function.
import numpy as np
myList = list(np.around(np.array(myList),2))
# OR
myList = np.around(myList,2).tolist()
how to limit or round a float to only two decimals without rounding up
rounding - How to round to 2 decimals with Python? - Stack Overflow
Floating point numbers to two decimal places - possible with standard lib?
How to round a whole number to 2 decimal places
Videos
Hello,
Does anyone know how to limit or round a float to only two decimals without rounding up?
for example,
if the number is 3.149, then I want the output to be 3.14. If the number is 3.0, then the output must be 3.00
thank you
You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.
In your case, it would be:
answer = str(round(answer, 2))
Using str.format()'s syntax to display answer with two decimal places (without altering the underlying value of answer):
def printC(answer):
print("\nYour Celsius value is {:0.2f}ºC.\n".format(answer))
Where:
:introduces the format spec0enables sign-aware zero-padding for numeric types.2sets the precision to2fdisplays the number as a fixed-point number