The number to be formatted.
An object containing various formatting options.
Optionalabbreviation?: booleanIf true, the number will be abbreviated (e.g., 1,200,000 becomes "1.2M"). Defaults to false.
Optionaldecimals?: numberThe number of decimal places to round to.
Optionalfixed?: booleanIf true, the number will be displayed with a fixed number of decimal places as specified by decimals, padding with zeros if necessary. Defaults to false.
OptionalnearestInteger?: numberThe base to which the number should be rounded (e.g., 10 for rounding to the nearest ten, 100 for nearest hundred).
Optionalposition?: booleanIf true, formats the number as an ordinal position (e.g., "1st", "2nd" in English, "1er", "2e" in French).
Optionalprefix?: stringA string to prepend before the formatted number.
Optionalround?: booleanIf true, the number will be rounded to the nearest integer or based on decimals, significantDigits, or nearestInteger options. Defaults to false.
Optionalsign?: booleanIf true, a "+" sign will be prepended to positive numbers. Negative numbers always retain their "-" sign. Defaults to false.
OptionalsignificantDigits?: numberThe number of significant digits to round to.
Optionalstyle?: "cbc" | "rc"The formatting style to apply. Can be "cbc" (default, typically English with comma thousands separator and dot decimal) or "rc" (typically French with space thousands separator and comma decimal).
Optionalsuffix?: stringA string to append after the formatted number.
The formatted number as a string.
// Basic usage: Format a number with thousands separator.
const num1 = formatNumber(1234567.89);
console.log(num1); // "1,234,567.89"
// With sign and rounding to 0 decimals.
const num2 = formatNumber(1234.567, { sign: true, decimals: 0 });
console.log(num2); // "+1,235"
// French style with abbreviation.
const num3 = formatNumber(1234567, { style: "rc", abbreviation: true });
console.log(num3); // "1,2 M"
Formats a number according to specified style, rounding, and display options. This versatile function can handle various numerical formatting needs.
The function supports two main styles: "cbc" (Canadian Broadcasting Corporation style, typically English) and "rc" (Radio-Canada style, typically French), which dictate the thousands separator and decimal marker.