0

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)
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35

2 Answers2

0

This should work

print('{0.2f}'.format(num))

When you turn this string back into a float with float() the formatting is lost.

rdas
  • 20,604
  • 6
  • 33
  • 46
0

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}')
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153