Format number

4 snippets across 3 stacks — Python, JavaScript, Regular Expressions

Also written as number format

PYPython

f-strings (Formatted String Literals)

PY · Strings
syntax
f"text {expression}"
example
name = "Alice"
balance = 1234.5
print(f"User: {name}")
print(f"Balance: ${balance:,.2f}")
print(f"{'centered':^20}")
output
User: Alice
Balance: $1,234.50
      centered      

Note Since Python 3.12, f-strings can contain backslashes and nested quotes freely. You can also nest f-strings inside f-strings.

Number Formatting

PY · Numbers
syntax
f"{value:format_spec}"
example
price = 1234567.891
print(f"{price:,.2f}")
print(f"{0.856:.1%}")
print(f"{42:08b}")
print(f"{255:#06x}")
output
1,234,567.89
85.6%
00101010
0x00ff

Note Format spec mini-language: comma for grouping, .Nf for decimal places, % for percent, b/o/x for binary/octal/hex.

JSJavaScript

Locale Number Formatting

JS · Numbers & Math
syntax
new Intl.NumberFormat(locale, options).format(n)
example
const price = 1234567.89;
console.log(new Intl.NumberFormat("en-US", {
  style: "currency", currency: "USD"
}).format(price));
// "$1,234,567.89"

console.log(new Intl.NumberFormat("de-DE").format(price));
// "1.234.567,89"

Note Intl.NumberFormat handles thousands separators, currency symbols, percentages, and units correctly for any locale.

RXRegular Expressions

Number with Commas / Decimals

RX · Common Patterns
syntax
/^-?\d{1,3}(,\d{3})*(\.\d+)?$/
example
JS:  /^-?\d{1,3}(,\d{3})*(\.\d+)?$/.test('1,234,567.89')  // true
JS:  /^-?\d{1,3}(,\d{3})*(\.\d+)?$/.test('12,34')          // false
output
true, false (incorrect comma placement)

Note Validates US-formatted numbers with optional commas every 3 digits and optional decimal part. European formats swap comma and period -- adjust the pattern accordingly. The leading -? handles negative numbers.