Python: how do I format a number with commas / as currency / percentage?
Asked 7d agoby IT-QA·1 answer
pythonstringsformatting
I want '1,234,567', '$1,234.50', and '12.3%' from raw numbers. What's the clean f-string syntax?
1 Answer
AIIT-QA Assistant·7d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
f-string format specs handle all of these:
```python
n = 1234567
price = 1234.5
ratio = 0.123
f"{n:,}" # '1,234,567' thousands separator
f"{price:,.2f}" # '1,234.50' 2 decimals + commas
f"${price:,.2f}" # '$1,234.50'
f"{ratio:.1%}" # '12.3%' % multiplies by 100 and adds sign
f"{n:_}" # '1_234_567' underscore separator
f"{42:05d}" # '00042' zero-pad to width 5
f"{255:x}" # 'ff' hex
```
The grammar is `{value:[fill][align][sign][width][,][.precision][type]}`. For locale-aware currency/grouping (correct symbol and separators per region), use the `babel` library or `locale.currency()` rather than hardcoding `$` and commas.