Approach 2: Using Custom function
- Check if the number is less than 1e3, if it is then return the number as it is.
- If the number is greater than or equal to 1e3 and less than 1e6 then remove the last three digits and append the character ‘K’ to it.
- If the number is greater than or equal to 1e6 and less than 1e9 then remove the last six digits and append the character ‘M’ to it.
- If the number is greater than or equal to 1e9 and less than 1e12 then remove the last nine digits and append the character ‘B’ to it.
- If the number is greater than or equal to 1e12 remove the last 12 digits and append the character ‘T’ to it.
Example 2: This example implements the above approach.
// Input number
let n = 1232873425;
// Display input number
console.log(n);
// Function to convert
let convert = (n) => {
if (n < 1e3) return n;
if (n >= 1e3 && n < 1e6)
return +(n / 1e3).toFixed(1) + "K";
if (n >= 1e6 && n < 1e9)
return +(n / 1e6).toFixed(1) + "M";
if (n >= 1e9 && n < 1e12)
return +(n / 1e9).toFixed(1) + "B";
if (n >= 1e12) return +(n / 1e12).toFixed(1) + "T";
};
// Function to display converted output
function GFG_Fun() {
// Display output
console.log("Number = " + convert(n));
}
// Funcion call
GFG_Fun();
Output
1232873425 Number = 1.2B
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.