Home > sculp-js > formatNumber
formatNumber() function
Formats a number into a string with comma thousands separators.
When decimals is omitted, the input is truncated to an integer (like parseInt) and grouped. When decimals is provided, the value is rounded to that many fraction digits. By default the requested precision is always emitted – formatMoney(1000, 2) yields '1,000.00' – which keeps monetary and tabular columns aligned, matching Number#toFixed and the minimumFractionDigits behavior of Intl.NumberFormat.
Pass trimZeros to opt into dynamic precision instead: trailing zeroes are removed and the decimal point is dropped when no fraction remains, so the output reflects whether the original value actually carried a fraction (analogous to Intl's maximumFractionDigits-only behavior).
Non-finite values are always rendered symbolically as NaN, ∞ or -∞ with no fraction attached, since they do not represent a decimal quantity.
Signature:
export declare function formatNumber(num: number | string, decimals?: number, trimZeros?: boolean): string;Parameters
Parameter | Type | Description |
|---|---|---|
num | number | string | the number or numeric string to format |
decimals | number | (Optional) the number of fraction digits to keep; non-positive values are treated as |
trimZeros | boolean | (Optional) when |
Returns:
string
{string} the formatted number string
Example
formatNumber(1234567.891); // => '1,234,567' (truncated without decimals)
formatNumber(98765.4321, 2); // => '98,765.43'
formatNumber(1234567.891, 3); // => '1,234,567.891'
formatNumber(3.14159, 4); // => '3.1416' (honours the requested 4 digits)
// Forced precision (default) – always emits `decimals` fraction digits
formatNumber(1000, 2); // => '1,000.00'
formatMoney(0, 2); // => '0.00'
// Dynamic precision – fraction only shown when it is significant
formatNumber(1000, 2, true); // => '1,000'
formatNumber(1000.5, 2, true); // => '1,000.5'
formatNumber(1000.05, 2, true); // => '1,000.05'
// Non-finite values never carry a fraction
formatNumber(NaN, 2); // => 'NaN'
formatNumber(Infinity, 2); // => '∞'