How to useIntl.NumberFormat in Javascript
In this approach, we can utilize the Intl.NumberFormat object in JavaScript to format the number according to a specified locale. By specifying a maximum significant digits count and using the notation property with the “compact” option, we can automatically abbreviate the number based on its magnitude.
Example:
// Function to convert a long number to an abbreviated string using Intl.NumberFormat
function convertToAbbreviation(number) {
// Create a new Intl.NumberFormat object with options
const formatter = new Intl.NumberFormat('en', {
notation: 'compact',
compactDisplay: 'short',
maximumSignificantDigits: 3
});
// Format the number and return the result
return formatter.format(number);
}
// Examples
console.log(convertToAbbreviation(1234)); // Output: 1.23k
console.log(convertToAbbreviation(1234567)); // Output: 1.23M
console.log(convertToAbbreviation(1234567890)); // Output: 1.23B
console.log(convertToAbbreviation(1234567890123)); // Output: 1.23T
Output
1.23K 1.23M 1.23B 1.23T
How to convert long number into abbreviated string in JavaScript ?
In this article, we are given a long number and the task is to convert it to the abbreviated string(eg.. 1234 to 1.2k). Here 2 approaches are discussed with the help of JavaScript.