💯 Formats a number for reading, with locale-aware grouping and rounding.

The plain case the rest of the module builds on: formatBytes, formatCurrency and formatCompact each format a number as something; this is the one that formats it as itself.

Syntax

TypeScript
import { formatNumber } from '@opentf/std';
formatNumber(value: number, options?: FormatNumberOptions): string;

Parameters

NameTypeDefaultDescription
valuenumberThe number to format.
options.stylestring'decimal'Either 'decimal' or 'percent'.
options.localestringThe locale (default runtime locale).
options.groupingbooleantrueWhether to group the thousands.
options.minFractionnumberThe minimum fraction digits.
options.maxFractionnumberThe maximum fraction digits.

Returns

The formatted number string. Throws a RangeError if an option is outside the range it allows.

Examples

Grouping separators and the decimal mark follow the locale:

TypeScript
formatNumber(1234567.891) //=> '1,234,567.891'
formatNumber(1234.5, { locale: 'de-DE' }) //=> '1.234,5'
formatNumber(1234.5, { grouping: false }) //=> '1234.5'

Rounding:

TypeScript
formatNumber(1234.5678, { maxFraction: 2 }) //=> '1,234.57'
formatNumber(7, { minFraction: 2 }) //=> '7.00'

style: 'percent' multiplies by 100, so the value is a ratio, not a number of percent:

TypeScript
formatNumber(0.42, { style: 'percent' }) //=> '42%'
formatNumber(0.4235, { style: 'percent', maxFraction: 1 }) //=> '42.4%'
Last updated on
Edit this page