The JavaScript Intl object
Raymond Camden[1] uses the compact
notation option of the Intl.NumberFormat
function to create abbreviated number formats.
To format the number 12499 into 12K, all you have to do is:
let value = 12499;
let shortNotation = new Intl.NumberFormat('en-US', {
notation:'compact'
}).format(value);
console.log(shortNotation); //12K
A longer notation, like formatting 12499 into 12 thousand, can be achieved with the compactDisplay
option:
let value = 12499;
let longNotation = new Intl.NumberFormat('en-US', {
notation:'compact',
compactDisplay: 'long'
}).format(value);
console.log(longNotation); //12 thousand
The Intl.NumberFormat
allows to control many more things, with just a little configuration, like currency formatting, rounding, and units. It will return localized, beautiful formattings. And while you are around, look at what other great things Intl
can do, such as Plural Rules, List Formats, and Relative Time Formats. I was not aware. Check out the the Intl Explorer[2].
Using Intl for Short Number Formatting, Raymond Camden, Jan 4, 2023 ↩︎
Comments