Solved

How do I show only 2 decimal places in an f-string?

TomBeckerOP

print(f"Distance: {distance}") shows 384399.123456. I want 384399.12.

4

Comments 5

Join the discussion

Already have an account? Log in

  1. OliviaPy Solutionreplies: 2

    Add a format spec after a colon:

    print(f"Distance: {distance:.2f} km")

    .2f means "fixed-point, 2 decimals". You can also add thousands separators: {distance:,.2f} gives 384,399.12.

    5
    1. TomBeckerOPreplies: 1

      The comma one is perfect for my report. Is there a list of these codes somewhere?

      -1
      1. LiamByte

        Search for "format specification mini-language" in the Python docs. The common ones are .2f, ,, % (percent) and >10 / <10 for alignment.

        1
    2. EmmaCodesreplies: 1

      Careful: .2f rounds for display only, the variable still has all its decimals. Bit me once when I compared values.

      6
      1. AmeliaRuns

        Good point, that's a nice difference between formatting and round().

        2