1

In Python, when I execute the following statement:

'{:.0}'.format(0.55) # 0.6

it evaluates to the string '0.6', however what I expected was the string '1'.

However, when I state the type symbol 'f', somehow what I expect is exactly what I get.

'{:.0f}'.format(0.55) # 1

What does the 'f' symbol do here? Why does the format string without 'f' not produce the outcome that I wanted?

coderboy
  • 1,710
  • 1
  • 6
  • 16
  • 2
    It's the presentation type specifier. From https://docs.python.org/3.4/library/string.html#formatspec. `f`: *Fixed point. Displays the number as a fixed-point number. The default precision is 6.* – user2390182 Feb 02 '21 at 14:01
  • @coderboy They closed the question but it was not well replyed... Anyway the default modifier for formatting float to string is `g`, so actually your `'{:.0}'.format(0.55)` is equivalent to `'{:.0g}'.format(0.55)`, now you can watch what `g` means into the float table in [python docs](https://docs.python.org/3/library/string.html#formatstrings) – DDomen Feb 02 '21 at 14:12
  • If you do not add 'f', it will be 'g' by default. This is from help('FORMATTING'): None: Similar to "'g'", except that fixed-point notation, when used, has at least one digit past the decimal point. The default precision is as high as needed to represent the particular value. The overall effect is to match the output of "str()" as altered by the other format modifiers. – Autumnii Feb 02 '21 at 14:12

0 Answers0