Solved How do I show only 2 decimal places in an f-string? TOTomBeckerOP 18 Sep, 17:37 print(f"Distance: {distance}") shows 384399.123456. I want 384399.12.
OLOliviaPy18 Sep, 22:10 Solutionreplies: 2Add 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.
TOTomBeckerOP20 Sep, 07:30replies: 1The comma one is perfect for my report. Is there a list of these codes somewhere?
LILiamByte20 Sep, 08:37Search for "format specification mini-language" in the Python docs. The common ones are .2f, ,, % (percent) and >10 / <10 for alignment.
EMEmmaCodes20 Sep, 14:10replies: 1Careful: .2f rounds for display only, the variable still has all its decimals. Bit me once when I compared values.
Comments 5
Join the discussion CommentAlready have an account? Log in
Add a format spec after a colon:
.2fmeans "fixed-point, 2 decimals". You can also add thousands separators:{distance:,.2f}gives 384,399.12.The comma one is perfect for my report. Is there a list of these codes somewhere?
Search for "format specification mini-language" in the Python docs. The common ones are
.2f,,,%(percent) and>10/<10for alignment.Careful:
.2frounds for display only, the variable still has all its decimals. Bit me once when I compared values.Good point, that's a nice difference between formatting and
round().