6

I'm really curious about why the behaviour is so different when add this "f" to the end of the number which I want to display:

# CASE with f
float1 = 10.1444786

print(f"{float1:.4f}")
# print out: 10.1445

# CASE without f
print(f"{float1:.4}")
# print out: 10.14

Why only 2 characters are displayed in the second example?

Vesa95
  • 607
  • 1
  • 7
  • 26
  • @MauriceMeyer Then please explain how truncating to 4 characters yields an output of 5 characters :) – Thomas Apr 13 '21 at 18:31
  • 1
    Note this has nothing to do with f-strings, e.g. `print("{:.4f}".format(float1))` vs. `print("{:.4}".format(float1))` – Chris_Rands Apr 13 '21 at 18:35

1 Answers1

7

The implied type specifier is g, as given in the documentation Thanks @Barmar for adding a comment with this info!

None: 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.

For Decimal, this is the same as either 'g' or 'G' depending on the value of context.capitals for the current decimal context.

The overall effect is to match the output of str() as altered by the other format modifiers.

An experiment:

for _ in range(10000):
    r = random.random() * random.randint(1, 10)
    assert f"{r:.6}" == f"{r:.6g}"

Works every time

From https://docs.python.org/3/library/string.html#formatstrings,

General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1.

So in your second example, you ask for 4 sigfigs, but in your first you ask for 4 digits of precision.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 2
    This is stated in the [documentation](https://docs.python.org/3/library/string.html#format-specification-mini-language): **None: 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.** – Barmar Apr 13 '21 at 18:32