Understanding float formatting

Viewed 90

I have written the following code:

x = 0.01
print(format(x, '0.27f'))
print(format(x, '1.27f'))
print(format(x, '2.27f'))

All the above print statements, are giving below output:

0.010000000000000000208166817

Please help me understand the difference between '0.27f' and '1.27f' and '2.27f'

2 Answers

The first number in the format string is the total width, not the width to the left of the decimal point. It is ignored if there are other factors forcing the representation to be longer, like the 27 places you've requested to the right of the decimal in all 3 examples.

By making the total width large enough you can start to see the difference, e.g.

print(format(x, '30.27f'))
 0.010000000000000000208166817
print(format(x, '31.27f'))
  0.010000000000000000208166817
print(format(x, '32.27f'))
   0.010000000000000000208166817

Try

print(format(x, '100.27f'))

The answer is padding.

Related