How do you format a floating-point number to a fixed width and decimal precision in Python? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you format a floating-point number to a fixed width and decimal precision in Python?

message-square
0

Use an f-string format specification of the form f"{value:width.precisionf}"—such as f"{3.14159:8.2f}" (which pads with leading spaces to a total width of 8 characters and rounds to 2 decimal places, producing " 3.14")—adding alignment (<, >, ^), zero-padding (08.2f), or thousands separators (10,.2f) right inside the format specifier as needed.

Basic Example

price = 49.5
tax = 4.2367

# 1. Recommended: Fixed total width (10 chars, right-aligned by default) + 2 decimal places
print(f"|{price:10.2f}|")
# Output: |     49.50|

print(f"|{tax:10.2f}|")
# Output: |      4.24|

# 2. Left-aligned (`<`), zero-padded (`0`), and thousands-separated (`,`):
big_val = 1234.567
print(f"|{big_val:<12.2f}|")   # Left-aligned in 12 chars:  |1234.57     |
print(f"|{big_val:012.2f}|")   # Zero-padded to 12 chars:   |000001234.57|
print(f"|{big_val:12,.2f}|")   # Comma thousands + 2 dec:   |    1,234.57|

# 3. Dynamic width & precision passed via variables (nested `{}`):
width, precision = 9, 3
print(f"|{tax:{width}.{precision}f}|")
# Output: |    4.237|

Key Details & Edge Cases

  • width is the minimum total character count (including the decimal point, minus sign, and commas):
    • In f"{-12.345:8.2f}", the formatted string "-12.35" uses 6 characters (-, 1, 2, ., 3, 5), so Python prepends 2 leading spaces to reach width 8 (" -12.35"). If the formatted number exceeds width (e.g., f"{123456.78:5.2f}"), Python never truncates digits—it expands beyond width automatically so numeric values are never corrupted.
  • Sign-aware zero-padding (08.2f vs. 0>8.2f):
    • Writing f"{-3.5:08.2f}" places zeros after the minus sign ("-0003.50"), whereas f"{-3.5:0>8.2f}" places zeros before the minus sign ("000-3.50"). Always use 08.2f (without >) for standard numeric zero-padding.
  • Banker’s rounding (round-half-to-even) in f"{val:.2f}":
    • Python’s f format specifier rounds halves to the nearest even digit (f"{2.675:.2f}" $\rightarrow$ "2.68", f"{2.685:.2f}" $\rightarrow$ "2.68"), and binary float representation inaccuracies (2.675 stored as 2.6749999999999998...) can occasionally round down unexpectedly. Use decimal.Decimal (Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) for exact financial/currency rounding.
  • Fixed decimal places (f) vs. significant digits (g) vs. scientific notation (e):
    • .2f enforces exact digits after the decimal point (padding trailing zeros: 5 $\rightarrow$ "5.00").
    • .4g formats to 4 total significant digits and strips trailing zeros (12.3456 $\rightarrow$ "12.35", 5.0 $\rightarrow$ "5").
    • .2e formats in scientific notation (1234.5 $\rightarrow$ "1.23e+03").
  • Formatting NumPy arrays or Pandas DataFrames cleanly:
    • f-string format specifiers work on scalar floats (float, np.float64, Decimal), not directly on whole lists or arrays (TypeError: unsupported format string passed to list.__format__). For NumPy arrays, use np.array2string(arr, formatter={"float_kind": lambda x: f"{x:8.2f}"}) or np.set_printoptions(precision=2, suppress=True); for Pandas DataFrames, use df.style.format("{:8.2f}") or pd.options.display.float_format = "{:8.2f}".format.

Comparison of Float Width & Precision Formatting Methods in Python

Method Syntax Example Supports Dynamic Width/Precision Variables? Exact Financial Rounding (ROUND_HALF_UP)? Best Used When
f-String Format Specifier (Recommended) f"{val:10.2f}" Yes (f"{val:{w}.{p}f}") No (binary float + round-half-to-even) Console tables, logs, reports, and general string formatting in Python 3.6+.
str.format() Method "{:10.2f}".format(val) Yes ("{:{w}.{p}f}".format(val, w=10, p=2)) No Reusable format templates stored in configuration files or variables.
Built-in format() Function format(val, "10.2f") Yes (format(val, f"{w}.{p}f")) No Formatting a single standalone value without surrounding literal text.
decimal.Decimal + f-String f"{Decimal('2.675'):10.2f}" Yes Yes (configurable via decimal context / .quantize()) Monetary, accounting, and tax calculations where binary float rounding errors are unacceptable.