I want number from input to print out with 2 decimal places. You can assume that the number will always be a float.
num = 20.0
Desired output - 20.00
.
I've tried this code:
num = round(num, 2)
num = float('{0.2f}'.format(num))
print(num)
I want number from input to print out with 2 decimal places. You can assume that the number will always be a float.
num = 20.0
Desired output - 20.00
.
I've tried this code:
num = round(num, 2)
num = float('{0.2f}'.format(num))
print(num)
This should work
print('{0.2f}'.format(num))
When you turn this string back into a float with float()
the formatting is lost.
No matter what you do to the float value, as long as it is still a float, it does not have any internal concept of decimal places.
If you want to display two decimal places, then that happens when you convert to text - which everything you print
is, whether you asked for the conversion or not. You cannot make num
"be" 20.00
as opposed to 20.0
, because those aren't actually different things. (And keep in mind that the float simply cannot represent all decimal values exactly.)
Therefore, we use string formatting in the print call:
num = 20.0
print('{.2f}'.format(num))
# Or, using f-strings:
print(f'{num:.2f}')