2

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'

martineau
  • 119,623
  • 25
  • 170
  • 301
meallhour
  • 13,921
  • 21
  • 60
  • 117
  • 2
    And if you're curious why there's a bunch of non-zero digits on the right, see [Is floating point math broken?](https://stackoverflow.com/q/588004/5987) – Mark Ransom Dec 04 '21 at 18:39

2 Answers2

7

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
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Can you please explain using an example? this will give a more clear picture – meallhour Dec 04 '21 at 18:45
  • @meallhour I added an example, if it still isn't clear just let me know. – Mark Ransom Dec 04 '21 at 18:50
  • I understand it now. So, by making the total width larger, are we adding extra spaces on the left side? – meallhour Dec 04 '21 at 18:54
  • @meallhour yes that's the default behavior. I know there are flags to change the alignment, for example if you put in a leading zero it will fill with zeros instead of spaces. Looking at the documentation for the format string will show all the possibilities. – Mark Ransom Dec 04 '21 at 19:22
0

Try

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

The answer is padding.

Mr.Mike
  • 51
  • 5