💯 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
| Name | Type | Default | Description |
|---|---|---|---|
| value | number | The number to format. | |
| options.style | string | 'decimal' | Either 'decimal' or 'percent'. |
| options.locale | string | The locale (default runtime locale). | |
| options.grouping | boolean | true | Whether to group the thousands. |
| options.minFraction | number | The minimum fraction digits. | |
| options.maxFraction | number | The 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%'