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.

Frequently asked questions

How do you format number?
This task is covered in 3 stacks on this page: Python, JavaScript, Regular Expressions. The "f-strings (Formatted String Literals)" snippet in Python uses `f"text {expression}"`.
Which code does the Python example use?
The "f-strings (Formatted String Literals)" snippet uses `f"text {expression}"`, from the Strings section of the Python cheat sheet.
Which stacks cover "format number" on this page?
Python, JavaScript, Regular Expressions. Together they hold 4 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "f-strings (Formatted String Literals)": Since Python 3.12, f-strings can contain backslashes and nested quotes freely. You can also nest f-strings inside f-strings.