'How to write Numbers in the Compact-String Format in Javascript
The Compact String Form for writing numbers is recommended by some Style Guides for writing large numbers so that they are easily read and interpreted. Often used in newspapers and magazines.
⚠️ Note ⚠️: This must not be confused with writing numbers in their full-textual form which is a different requirement (commonly known as numbers to full words conversion) and had been answered extensively on StackOverflow.
Some examples,
the number 22000000 would be written as 22 million,
the number 77560000000 would be written as 77 billion 560 million,
However, for numbers below 11 (1 to 10) the word is used, for example:
the number 3000000 would be written as three million.
Numbers below 1000 will remain in their number form.
Other use examples include:
text : Production exceeded 257456 units last year
becomes : Production exceeded 257 thousand and 456 units last year
text : Profits exceeded 25000000 US Dollars last year
becomes : Profits exceeded 25 million US Dollars last year
text : 2000000 people attended the Olympic games
becomes : Two million people attended the Olympic games
Solution 1:[1]
The following function numToCompactWords(number) converts a number to its Compacted Number-Words equivalent.
An additional function stringToCompact(string) takes an input as a string and returns a string with integer numbers converted to compact number-words format using the numToCompactWords(number) function. This function can be improved to handle (say) decimal numbers as necessary and skip numbers inside quotes if needed. However, I have added it to give a simple use-example.
Included below are some test cases together with example textual ouputs.
/********************************************************
* @function : numToCompactWords(number)
* @purpose : Converts numbers to Compacted Number-Words
* @version : 1.00
* @author : Mohsen Alyafei
* @date : 11 Mar 2022
* @param : {number} integer numeric or string
* @param : [smart] flag (default true);
* false: uses numbers always even for numbers below 10
* @returns : {string} The Compacted Number-Words string
********************************************************/
function numToCompactWords(num=0,smart=true) {
if (num == 0) return "zero";
num = ("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
let out="", scale=["","thousand","million","billion","trillion","quadrillion"];
return num.forEach((n,i) => {
n=+n;
if (n) {
if (smart && n<11) n=["","one","two","three","four","five","six","seven","eight","nine","ten"][n];
let L=num.length-i-1;
out+= (L || num<=999 ?"":" and") + (out?" ":"") + n + (scale[L]?" ":"") + scale[L];
}
}),out;
}
//=========================================
// Test Code
//=========================================
var r=0; // test tracker
r |= test(0,"zero");
r |= test(5,"five");
r |= test(10,"ten");
r |= test(19,"19");
r |= test(33,"33");
r |= test(100,"100");
r |= test(111,"111");
r |= test(890,"890");
r |= test(1234,"one thousand and 234");
r |= test(12345,"12 thousand and 345");
r |= test(123456,"123 thousand and 456");
r |= test(1234567,"one million 234 thousand and 567");
r |= test(12345678,"12 million 345 thousand and 678");
r |= test(123456789,"123 million 456 thousand and 789");
r |= test(1234567890,"one billion 234 million 567 thousand and 890");
r |= test(12012,"12 thousand and 12");
r |= test(120012,"120 thousand and 12");
r |= test(1200012,"one million 200 thousand and 12");
r |= test(12000012,"12 million and 12");
r |= test(120000012,"120 million and 12");
r |= test(75075,"75 thousand and 75");
r |= test(750075,"750 thousand and 75");
r |= test(7500075,"seven million 500 thousand and 75");
r |= test(75000075,"75 million and 75");
r |= test(750000075,"750 million and 75");
r |= test(1000,"one thousand");
r |= test(2000000,"two million");
r |= test(10000000000,"ten billion");
r |= test(5000000000000,"five trillion");
r |= test("1000000000000000","one quadrillion");
if (r==0) console.log("All Test Units Passed.");
//============================================
function stringToCompact(s){
s =s.trimStart().split(" ");
for (let i in s)
if (Number.isInteger(+s[i])) {
s[i] =numToCompactWords(s[i]);
if (i==0) s[i]=s[i].charAt(0).toUpperCase()+s[i].substring(1);
}
return s.join(" ");
}
//============================================
console.log("-".repeat(50));
console.log("Examples to Convert numbers inside text:")
console.log("-".repeat(50));
console.log(stringToCompact("Over 120000 attended the exhibition last week"));
console.log(stringToCompact("World population is 7750000000"));
console.log(stringToCompact("Production exceeded 257456 units last year"));
console.log(stringToCompact("Profits exceeded 25000000 US Dollars last year"));
console.log(stringToCompact("There are 20000 books and 25 magazines"));
console.log(stringToCompact("2000000 people attended the Olympic games"));
//============================================
function test(n,should) {
let result = numToCompactWords(n);
if (result !== should) {console.log(`${n} Output : ${result}\n${n} Should be: ${should}`);return 1;}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohsen Alyafei |
