0

Consider following snippet:

for value in [1.123, 1.126, 1.12, 1.16, 1.1, 1.0, 12345.6789]:
    print(
        f'Testing {value:>12}',
        f'.2 {value:>17.2}',
        f'.2g {value:>16.2g}',
        f'.2f {value:>16.2f}',
        end='\n\n',
        sep='\n'
    )

The code shows that {value:.2} and {value:.2f} output different results.

The output:

Testing        1.123
.2               1.1
.2g              1.1
.2f             1.12

Testing        1.126
.2               1.1
.2g              1.1
.2f             1.13

Testing         1.12
.2               1.1
.2g              1.1
.2f             1.12

Testing         1.16
.2               1.2
.2g              1.2
.2f             1.16

Testing          1.1
.2               1.1
.2g              1.1
.2f             1.10

Testing          1.0
.2               1.0
.2g                1
.2f             1.00

Testing   12345.6789
.2           1.2e+04
.2g          1.2e+04
.2f         12345.68

The .2f specifier converts the number to fixed-point notation. I found out that .2 and .2g are similar but not quite.

What is the intended behaviour of the .2 specifier?

sanitizedUser
  • 1,723
  • 3
  • 18
  • 33

1 Answers1

2

The documentation says:

Type: None
Meaning: For float this is the same as 'g', except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully.

which I read as saying that when no suffix (such as f) is given, style g is used for floats, except that cases like 1.0:.2 will include the .0 ("at least one digit past the decimal point"), whereas 1.0:.2g will not.

The description for g includes specifying

... insignificant trailing zeros are removed.

khelwood
  • 55,782
  • 14
  • 81
  • 108