How to convert long number into abbreviated string in JavaScript ?
Last Updated :
04 Jul, 2024
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.
Approaches to Convert Long Number to Abbreviated String:
Approach 1: Using JavaScript methods
- Get the characters in an array(ar = ["", "k", "m", "b"])
- Divide the length of the number by 3 and get the value in var(sNum).
- If the sNum != 0 then calculate the precise value of the number by dividing it by 1000^sNum.
- Append the character at index = sNum in the array, to the precise value to finally get the abbreviated number.
Example 1: This example implements the above approach.
JavaScript
// Input number
let n = 123287342;
// Display input number
console.log(n);
// Function to convert number
function convert(val) {
// Thousands, millions, billions etc..
let s = ["", "k", "m", "b", "t"];
// Dividing the value by 3.
let sNum = Math.floor(("" + val).length / 3);
// Calculating the precised value.
let sVal = parseFloat(
(sNum != 0
? val / Math.pow(1000, sNum)
: val
).toPrecision(2)
);
if (sVal % 1 != 0) {
sVal = sVal.toFixed(1);
}
// Appending the letter to precised val.
return sVal + s[sNum];
}
// Function to show converted output
function GFG_Fun() {
// Display output
console.log("Number = " + convert(n));
}
GFG_Fun();
Output123287342
Number = 0.1b
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.
JavaScript
// 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();
Output1232873425
Number = 1.2B
Approach 3: Using logarithms
This approach involves using logarithms to determine the appropriate abbreviation for the number. We can take the logarithm base 10 of the given number to find its order of magnitude, which indicates the number of digits in the number. Then, we divide this order of magnitude by 3 to determine the appropriate index in the abbreviation array. Finally, we divide the number by 1000(order of magnitude/3) and append the corresponding abbreviation from the array.
JavaScript
// Input number
let n = 1232873425;
// Display input number
console.log(n);
// Function to convert
let convert = (n) => {
// Abbreviation array
let s = ["", "k", "m", "b", "t"];
// Find the order of magnitude
let orderOfMagnitude = Math.floor(Math.log10(n));
// Determine the index in the abbreviation array
let index = Math.floor(orderOfMagnitude / 3);
// Calculate the abbreviated value
let abbreviatedValue = parseFloat((n / Math.pow(1000, index)).toPrecision(2));
// Append the abbreviation
return abbreviatedValue + s[index];
};
// Function to display converted output
function GFG_Fun() {
// Display output
console.log("Number = " + convert(n));
}
// Function call
GFG_Fun();
Output1232873425
Number = 1.2b
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:
JavaScript
// 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
Output1.23K
1.23M
1.23B
1.23T
Approach 5: Using Recursion
This approach uses a recursive function to divide the number by 1000 and add the corresponding suffix ('K', 'M', 'B', 'T') until the number is less than 1000. This approach ensures the number is appropriately abbreviated for any magnitude.
This recursive approach is concise and elegant, handling any magnitude by breaking down the problem into smaller subproblems and solving each iteratively.
JavaScript
// Input number
let n = 1232873425;
// Display input number
console.log(n);
// Recursive function to convert number
function convert(n, suffix = '') {
// Suffix array for thousands, millions, billions, etc.
let suffixes = ['', 'K', 'M', 'B', 'T'];
// Base case: if n is less than 1000, return the number with the suffix
if (n < 1000) {
return n.toFixed(1) + suffix;
}
// Recursive case: divide the number by 1000 and add the next suffix
let index = suffix ? suffixes.indexOf(suffix) + 1 : 1;
return convert(n / 1000, suffixes[index]);
}
// Function to display converted output
function GFG_Fun() {
// Display output
console.log("Number = " + convert(n));
}
// Function call
GFG_Fun();
Output1232873425
Number = 1.2B
Approach 6: Using External Library: numeral.js
Using the numeral.js library, convert a long number into an abbreviated string by formatting it with numeral(number).format('0.0a'). This method simplifies number abbreviation, automatically handling large values like thousands (`k`), millions (`m`), and billions (`b`).
Example
JavaScript
// Import the numeral library
const numeral = require('numeral');
// Example long number
const number = 1234567890;
// Convert the number to an abbreviated string
const abbreviatedNumber = numeral(number).format('0.0a');
// Output the result
console.log(abbreviatedNumber);
Output:
1.2b
Similar Reads
How to create a Number object using JavaScript ? In this article, we will discuss how to create a Number object using JavaScript. A number object is used to represent integers, decimal or float point numbers, and many more. The primitive wrapper object Number is used to represent and handle numbers. examples: 20, 0.25. We generally don't need to w
2 min read
How to convert a value to a safe integer using JavaScript ? In this article, we will learn How to convert a value to a safe integer using JavaScript. We have given a number, and we have to convert it into a safe integer using JavaScript. Safe Integers are integers between -(253 - 1) and (253 - 1). Approach: First, we take input using the prompt in JavaScript
2 min read
How to add float numbers using JavaScript ? Given two or more numbers the task is to get the float addition in the desired format with the help of JavaScript. There are two methods to solve this problem which are discussed below: Table of Content Using parseFloat() and toFixed() method Using parseFloat() and Math.round() method Using Number()
2 min read
Calculate current week number in JavaScript Calculating the current week number involves determining which week of the year the current date falls into. The method of calculation can vary slightly depending on the rules you follow, such as which day starts the week (Sunday or Monday) and how the first week of the year is defined.For example:J
2 min read
How to Convert a Float Number to the Whole Number in JavaScript? Given a float number and the task is to convert a float number to a whole number using JavaScript. Below are various methods to convert float numbers to whole numbers in JavaScript:Table of ContentMath.floor (floating argument)Math.ceil (floating argument) Math.round (floating argument)Math.trunc (f
4 min read
How to convert Number to Boolean in JavaScript ? We convert a Number to Boolean by using the JavaScript Boolean() method and double NOT operator(!!). A JavaScript boolean results in one of two values i.e. true or false. However, if one wants to convert a variable that stores integer â0â or â1â into Boolean Value i.e. "false" or "true". Below are
2 min read
Convert a Number to a String in JavaScript These are the following ways to Convert a number to a string in JavaScript:1. Using toString() Method (Efficient and Simple Method)This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type.JavaScriptlet a = 20; console.log(a
1 min read
Convert a negative number to positive in JavaScript In this article, we will see how we can convert a negative number to a positive number in JavaScript by the methods described below. Below are the methods to convert a negative number to a positive in JavaScript: Table of Content Multiplying by -1Using Math.abs()adding a minus signFlipping the bitUs
4 min read
Check a Number is Prime or Not Using JavaScript A prime number is a whole number greater than 1, which has no positive divisors other than 1 and itself. In other words, prime numbers cannot be formed by multiplying two smaller natural numbers. For example:2, 3, 5, 7, 11, and 13 are prime numbers.4, 6, 8, 9, and 12 are not prime numbers because th
5 min read
JavaScript - Convert a Number into JS Array You have a number, like 12345, and you need to convert it into an array where each element represents a digit of the number. For example, 12345 should become [1, 2, 3, 4, 5]. How can you achieve this in JavaScript?In JavaScript, there are various ways to transform a number into an array of its digit
3 min read