Transform numbers to words in lakh / crore system - javascript

I'm writing some code that converts a given number into words, here's what I have got after googling. But I think it's a bit too long for such a simple task.
Two Regular Expressions and two for loops, I want something simpler.
I am trying to achieve this in as few lines of code as possible. here's what I've come up with so far:
Any suggestions?
var th = ['','thousand','million', 'billion','trillion'];
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g,'');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1)
x = s.length;
if (x > 15)
return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i=0; i < x; i++) {
if ((x-i)%3==2) {
if (n[i] == '1') {
str += tn[Number(n[i+1])] + ' ';
i++;
sk=1;
} else if (n[i]!=0) {
str += tw[n[i]-2] + ' ';
sk=1;
}
} else if (n[i]!=0) { // 0235
str += dg[n[i]] +' ';
if ((x-i)%3==0) str += 'hundred ';
sk=1;
}
if ((x-i)%3==1) {
if (sk)
str += th[(x-i-1)/3] + ' ';
sk=0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i=x+1; i<y; i++)
str += dg[n[i]] +' ';
}
return str.replace(/\s+/g,' ');
}
Also, the above code converts to the English numbering system like Million/Billion, I need the South Asian numbering system, like in Lakhs and Crores.

Update: Looks like this is more useful than I thought. I've just published this on npm. https://www.npmjs.com/package/num-words
Here's a shorter code. with one RegEx and no loops. converts as you wanted, in south asian numbering system
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function inWords (num) {
if ((num = num.toString()).length > 9) return 'overflow';
n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
if (!n) return; var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';
return str;
}
document.getElementById('number').onkeyup = function () {
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
<span id="words"></span>
<input id="number" type="text" />
The only limitation is, you can convert maximum of 9 digits, which I think is more than sufficient in most cases..

"Deceptively simple task." – Potatoswatter
Indeed. There's many little devils hanging out in the details of this problem. It was very fun to solve tho.
EDIT: This update takes a much more compositional approach. Previously there was one big function which wrapped a couple other proprietary functions. Instead, this time we define generic reusable functions which could be used for many varieties of tasks. More about those after we take a look at numToWords itself …
// numToWords :: (Number a, String a) => a -> String
let numToWords = n => {
let a = [
'', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
let b = [
'', '', 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
let g = [
'', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'
];
// this part is really nasty still
// it might edit this again later to show how Monoids could fix this up
let makeGroup = ([ones,tens,huns]) => {
return [
num(huns) === 0 ? '' : a[huns] + ' hundred ',
num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '',
a[tens+ones] || a[ones]
].join('');
};
// "thousands" constructor; no real good names for this, i guess
let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`;
// execute !
if (typeof n === 'number') return numToWords(String(n));
if (n === '0') return 'zero';
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(comp(not)(isEmpty))
.reverse()
.join(' ');
};
Here are the dependencies:
You'll notice these require next to no documentation because their intents are immediately clear. chunk might be the only one that takes a moment to digest, but it's really not too bad. Plus the function name gives us a pretty good indication what it does, and it's probably a function we've encountered before.
const arr = x => Array.from(x);
const num = x => Number(x) || 0;
const str = x => String(x);
const isEmpty = xs => xs.length === 0;
const take = n => xs => xs.slice(0,n);
const drop = n => xs => xs.slice(n);
const reverse = xs => xs.slice(0).reverse();
const comp = f => g => x => f (g (x));
const not = x => !x;
const chunk = n => xs =>
isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];
"So these make it better?"
Look at how the code has cleaned up significantly
// NEW CODE (truncated)
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(comp(not)(isEmpty))
.reverse()
.join(' ');
// OLD CODE (truncated)
let grp = n => ('000' + n).substr(-3);
let rem = n => n.substr(0, n.length - 3);
let cons = xs => x => g => x ? [x, g && ' ' + g || '', ' ', xs].join('') : xs;
let iter = str => i => x => r => {
if (x === '000' && r.length === 0) return str;
return iter(cons(str)(fmt(x))(g[i]))
(i+1)
(grp(r))
(rem(r));
};
return iter('')(0)(grp(String(n)))(rem(String(n)));
Most importantly, the utility functions we added in the new code can be used other places in your app. This means that, as a side effect of implementing numToWords in this way, we get the other functions for free. Bonus soda !
Some tests
console.log(numToWords(11009));
//=> eleven thousand nine
console.log(numToWords(10000001));
//=> ten million one
console.log(numToWords(987));
//=> nine hundred eighty-seven
console.log(numToWords(1015));
//=> one thousand fifteen
console.log(numToWords(55111222333));
//=> fifty-five billion one hundred eleven million two hundred
// twenty-two thousand three hundred thirty-three
console.log(numToWords("999999999999999999999991"));
//=> nine hundred ninety-nine sextillion nine hundred ninety-nine
// quintillion nine hundred ninety-nine quadrillion nine hundred
// ninety-nine trillion nine hundred ninety-nine billion nine
// hundred ninety-nine million nine hundred ninety-nine thousand
// nine hundred ninety-one
console.log(numToWords(6000753512));
//=> six billion seven hundred fifty-three thousand five hundred
// twelve
Runnable demo
const arr = x => Array.from(x);
const num = x => Number(x) || 0;
const str = x => String(x);
const isEmpty = xs => xs.length === 0;
const take = n => xs => xs.slice(0,n);
const drop = n => xs => xs.slice(n);
const reverse = xs => xs.slice(0).reverse();
const comp = f => g => x => f (g (x));
const not = x => !x;
const chunk = n => xs =>
isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];
// numToWords :: (Number a, String a) => a -> String
let numToWords = n => {
let a = [
'', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
let b = [
'', '', 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
let g = [
'', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'
];
// this part is really nasty still
// it might edit this again later to show how Monoids could fix this up
let makeGroup = ([ones,tens,huns]) => {
return [
num(huns) === 0 ? '' : a[huns] + ' hundred ',
num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '',
a[tens+ones] || a[ones]
].join('');
};
let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`;
if (typeof n === 'number')
return numToWords(String(n));
else if (n === '0')
return 'zero';
else
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(comp(not)(isEmpty))
.reverse()
.join(' ');
};
console.log(numToWords(11009));
//=> eleven thousand nine
console.log(numToWords(10000001));
//=> ten million one
console.log(numToWords(987));
//=> nine hundred eighty-seven
console.log(numToWords(1015));
//=> one thousand fifteen
console.log(numToWords(55111222333));
//=> fifty-five billion one hundred eleven million two hundred
// twenty-two thousand three hundred thirty-three
console.log(numToWords("999999999999999999999991"));
//=> nine hundred ninety-nine sextillion nine hundred ninety-nine
// quintillion nine hundred ninety-nine quadrillion nine hundred
// ninety-nine trillion nine hundred ninety-nine billion nine
// hundred ninety-nine million nine hundred ninety-nine thousand
// nine hundred ninety-one
console.log(numToWords(6000753512));
//=> six billion seven hundred fifty-three thousand five hundred
// twelve
You can transpile the code using babel.js if you want to see the ES5 variant

I spent a while developing a better solution to this. It can handle very big numbers but once they get over 16 digits you have pass the number in as a string. Something about the limit of JavaScript numbers.
function numberToEnglish( n ) {
var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g,"");
/* Is number zero? */
if( parseInt( string ) === 0 ) {
return 'zero';
}
/* Array of units as words */
units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
/* Array of tens as words */
tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
/* Array of scales as words */
scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
/* Split user argument into 3 digit chunks from right to left */
start = string.length;
chunks = [];
while( start > 0 ) {
end = start;
chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
}
/* Check if function has enough scale words to be able to stringify the user argument */
chunksLen = chunks.length;
if( chunksLen > scales.length ) {
return '';
}
/* Stringify each integer in each chunk */
words = [];
for( i = 0; i < chunksLen; i++ ) {
chunk = parseInt( chunks[i] );
if( chunk ) {
/* Split chunk into array of individual integers */
ints = chunks[i].split( '' ).reverse().map( parseFloat );
/* If tens integer is 1, i.e. 10, then add 10 to units integer */
if( ints[1] === 1 ) {
ints[0] += 10;
}
/* Add scale word if chunk is not zero and array item exists */
if( ( word = scales[i] ) ) {
words.push( word );
}
/* Add unit word if array item exists */
if( ( word = units[ ints[0] ] ) ) {
words.push( word );
}
/* Add tens word if array item exists */
if( ( word = tens[ ints[1] ] ) ) {
words.push( word );
}
/* Add 'and' string after units or tens integer if: */
if( ints[0] || ints[1] ) {
/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
if( ints[2] || ! i && chunksLen ) {
words.push( and );
}
}
/* Add hundreds word if array item exists */
if( ( word = units[ ints[2] ] ) ) {
words.push( word + ' hundred' );
}
}
}
return words.reverse().join( ' ' );
}
// - - - - - Tests - - - - - -
function test(v) {
var sep = ('string'==typeof v)?'"':'';
console.log("numberToEnglish("+sep + v.toString() + sep+") = "+numberToEnglish(v));
}
test(2);
test(721);
test(13463);
test(1000001);
test("21,683,200,000,621,384");

You might want to try it recursive. It works for numbers between 0 and 999999. Keep in mind that (~~) does the same as Math.floor
var num = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split(" ");
var tens = "twenty thirty forty fifty sixty seventy eighty ninety".split(" ");
function number2words(n){
if (n < 20) return num[n];
var digit = n%10;
if (n < 100) return tens[~~(n/10)-2] + (digit? "-" + num[digit]: "");
if (n < 1000) return num[~~(n/100)] +" hundred" + (n%100 == 0? "": " " + number2words(n%100));
return number2words(~~(n/1000)) + " thousand" + (n%1000 != 0? " " + number2words(n%1000): "");
}

I like the result I got here which i think is easy to read and short enough to fit as a solution.
function NumInWords (number) {
const first = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
const tens = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
const mad = ['', 'thousand', 'million', 'billion', 'trillion'];
let word = '';
for (let i = 0; i < mad.length; i++) {
let tempNumber = number%(100*Math.pow(1000,i));
if (Math.floor(tempNumber/Math.pow(1000,i)) !== 0) {
if (Math.floor(tempNumber/Math.pow(1000,i)) < 20) {
word = first[Math.floor(tempNumber/Math.pow(1000,i))] + mad[i] + ' ' + word;
} else {
word = tens[Math.floor(tempNumber/(10*Math.pow(1000,i)))] + '-' + first[Math.floor(tempNumber/Math.pow(1000,i))%10] + mad[i] + ' ' + word;
}
}
tempNumber = number%(Math.pow(1000,i+1));
if (Math.floor(tempNumber/(100*Math.pow(1000,i))) !== 0) word = first[Math.floor(tempNumber/(100*Math.pow(1000,i)))] + 'hunderd ' + word;
}
return word;
}
console.log(NumInWords(89754697976431))
And the result is :
eighty-nine trillion seven hundred fifty-four billion six hundred ninety-seven million nine hundred seventy-six thousand four hundred thirty-one

<html>
<head>
<title>HTML - Convert numbers to words using JavaScript</title>
<script type="text/javascript">
function onlyNumbers(evt) {
var e = event || evt; // For trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function NumToWord(inputNumber, outputControl) {
var str = new String(inputNumber)
var splt = str.split("");
var rev = splt.reverse();
var once = ['Zero', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'];
var twos = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
var tens = ['', 'Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];
numLength = rev.length;
var word = new Array();
var j = 0;
for (i = 0; i < numLength; i++) {
switch (i) {
case 0:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = '' + once[rev[i]];
}
word[j] = word[j];
break;
case 1:
aboveTens();
break;
case 2:
if (rev[i] == 0) {
word[j] = '';
}
else if ((rev[i - 1] == 0) || (rev[i - 2] == 0)) {
word[j] = once[rev[i]] + " Hundred ";
}
else {
word[j] = once[rev[i]] + " Hundred and";
}
break;
case 3:
if (rev[i] == 0 || rev[i + 1] == 1) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if ((rev[i + 1] != 0) || (rev[i] > 0)) {
word[j] = word[j] + " Thousand";
}
break;
case 4:
aboveTens();
break;
case 5:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if (rev[i + 1] !== '0' || rev[i] > '0') {
word[j] = word[j] + " Lakh";
}
break;
case 6:
aboveTens();
break;
case 7:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if (rev[i + 1] !== '0' || rev[i] > '0') {
word[j] = word[j] + " Crore";
}
break;
case 8:
aboveTens();
break;
// This is optional.
// case 9:
// if ((rev[i] == 0) || (rev[i + 1] == 1)) {
// word[j] = '';
// }
// else {
// word[j] = once[rev[i]];
// }
// if (rev[i + 1] !== '0' || rev[i] > '0') {
// word[j] = word[j] + " Arab";
// }
// break;
// case 10:
// aboveTens();
// break;
default: break;
}
j++;
}
function aboveTens() {
if (rev[i] == 0) { word[j] = ''; }
else if (rev[i] == 1) { word[j] = twos[rev[i - 1]]; }
else { word[j] = tens[rev[i]]; }
}
word.reverse();
var finalOutput = '';
for (i = 0; i < numLength; i++) {
finalOutput = finalOutput + word[i];
}
document.getElementById(outputControl).innerHTML = finalOutput;
}
</script>
</head>
<body>
<h1>
HTML - Convert numbers to words using JavaScript</h1>
<input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);" onkeyup="NumToWord(this.value,'divDisplayWords');"
maxlength="9" style="background-color: #efefef; border: 2px solid #CCCCC; font-size: large" />
<br />
<br />
<div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;">
</div>
</body>
</html>

I modified MC Shaman's code to fix the bug of single number having and appear before it
function numberToEnglish( n ) {
var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g,"");
/* Is number zero? */
if( parseInt( string ) === 0 ) {
return 'zero';
}
/* Array of units as words */
units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
/* Array of tens as words */
tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
/* Array of scales as words */
scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
/* Split user argument into 3 digit chunks from right to left */
start = string.length;
chunks = [];
while( start > 0 ) {
end = start;
chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
}
/* Check if function has enough scale words to be able to stringify the user argument */
chunksLen = chunks.length;
if( chunksLen > scales.length ) {
return '';
}
/* Stringify each integer in each chunk */
words = [];
for( i = 0; i < chunksLen; i++ ) {
chunk = parseInt( chunks[i] );
if( chunk ) {
/* Split chunk into array of individual integers */
ints = chunks[i].split( '' ).reverse().map( parseFloat );
/* If tens integer is 1, i.e. 10, then add 10 to units integer */
if( ints[1] === 1 ) {
ints[0] += 10;
}
/* Add scale word if chunk is not zero and array item exists */
if( ( word = scales[i] ) ) {
words.push( word );
}
/* Add unit word if array item exists */
if( ( word = units[ ints[0] ] ) ) {
words.push( word );
}
/* Add tens word if array item exists */
if( ( word = tens[ ints[1] ] ) ) {
words.push( word );
}
/* Add 'and' string after units or tens integer if: */
if( ints[0] || ints[1] ) {
/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
if( ints[2] || (i + 1) > chunksLen ) {
words.push( and );
}
}
/* Add hundreds word if array item exists */
if( ( word = units[ ints[2] ] ) ) {
words.push( word + ' hundred' );
}
}
}
return words.reverse().join( ' ' );
}
// - - - - - Tests - - - - - -
function figure(val) {
finalFig = numberToEnglish(val);
document.getElementById("words").innerHTML = finalFig;
}
<span id="words"></span>
<input id="number" type="text" onkeyup=figure(this.value) />

Update February 2021
Although this question is raised over 8 years ago with various solutions and answers, the easiest solution that can be easily updated to increase the scale by just inserting a name in the array without code modification; and also using very short code is the function below.
This solution is for the English reading of numbers (not the South-Asian System) and uses the standard US English (American way) of writing large numbers. i.e. it does not use the UK System (the UK system uses the word "and" like: "three hundred and twenty-two thousand").
Test cases are provided and also an input field.
Remember, it is "Unsigned Integers" that we are converting to words.
You can increase the scale[] array beyond Sextillion.
As the function is short, you can use it as an internal function in, say, currency conversion where decimal numbers are used and call it twice for the whole part and the fractional part.
Hope it is useful.
/********************************************************
* #function : integerToWords()
* #purpose : Converts Unsigned Integers to Words
* Using String Triplet Array.
* #version : 1.05
* #author : Mohsen Alyafei
* #date : 15 January 2021
* #param : {number} [integer numeric or string]
* #returns : {string} The wordified number string
********************************************************/
const Ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
Tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety","Hundred"],
Scale = ["","Thousand","Million","Billion","Trillion","Quadrillion","Quintillion","Sextillion"];
//==================================
const integerToWords = (n = 0) => {
if (n == 0) return "Zero"; // check for zero
n = ("0".repeat(2*(n+="").length % 3) + n).match(/.{3}/g); // create triplets array
if (n.length > Scale.length) return "Too Large"; // check if larger than scale array
let out= ""; return n.forEach((Triplet,pos) => { // loop into array for each triplet
if (+Triplet) { out+=' ' +(+Triplet[0] ? Ones[+Triplet[0]]+' '+ Tens[10] : "") +
' ' + (+Triplet.substr(1)< 20 ? Ones[+Triplet.substr(1)] :
Tens[+Triplet[1]] + (+Triplet[2] ? "-" : "") + Ones[+Triplet[2]]) +
' ' + Scale[n.length-pos-1]; }
}),out.replace(/\s+/g,' ').trim();}; // lazy job using trim()
//==================================
//=========================================
// Test Cases
//=========================================
var r=0; // test tracker
r |= test(0,"Zero");
r |= test(5,"Five");
r |= test(10,"Ten");
r |= test(19,"Nineteen");
r |= test(33,"Thirty-Three");
r |= test(100,"One Hundred");
r |= test(111,"One Hundred Eleven");
r |= test(890,"Eight Hundred Ninety");
r |= test(1234,"One Thousand Two Hundred Thirty-Four");
r |= test(12345,"Twelve Thousand Three Hundred Forty-Five");
r |= test(123456,"One Hundred Twenty-Three Thousand Four Hundred Fifty-Six");
r |= test(1234567,"One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven");
r |= test(12345678,"Twelve Million Three Hundred Forty-Five Thousand Six Hundred Seventy-Eight");
r |= test(123456789,"One Hundred Twenty-Three Million Four Hundred Fifty-Six Thousand Seven Hundred Eighty-Nine");
r |= test(1234567890,"One Billion Two Hundred Thirty-Four Million Five Hundred Sixty-Seven Thousand Eight Hundred Ninety");
r |= test(1001,"One Thousand One");
r |= test(10001,"Ten Thousand One");
r |= test(100001,"One Hundred Thousand One");
r |= test(1000001,"One Million One");
r |= test(10000001,"Ten Million One");
r |= test(100000001,"One Hundred Million One");
r |= test(12012,"Twelve Thousand Twelve");
r |= test(120012,"One Hundred Twenty Thousand Twelve");
r |= test(1200012,"One Million Two Hundred Thousand Twelve");
r |= test(12000012,"Twelve Million Twelve");
r |= test(120000012,"One Hundred Twenty Million Twelve");
r |= test(75075,"Seventy-Five Thousand Seventy-Five");
r |= test(750075,"Seven Hundred Fifty Thousand Seventy-Five");
r |= test(7500075,"Seven Million Five Hundred Thousand Seventy-Five");
r |= test(75000075,"Seventy-Five Million Seventy-Five");
r |= test(750000075,"Seven Hundred Fifty Million Seventy-Five");
r |= test(1000,"One Thousand");
r |= test(1000000,"One Million");
r |= test(1000000000,"One Billion");
r |= test(1000000000000,"One Trillion");
r |= test("1000000000000000","One Quadrillion");
r |= test("1000000000000000000","One Quintillion");
r |= test("1000000100100100100","One Quintillion One Hundred Billion One Hundred Million One Hundred Thousand One Hundred");
if (r==0) console.log("All Tests Passed.");
//=====================================
// Tester Function
//=====================================
function test(n,should) {
let result = integerToWords(n);
if (result !== should) {console.log(`${n} Output : ${result}\n${n} Should be: ${should}`);return 1;}
}
<input type="text" name="number" placeholder="Please enter an Integer Number" onkeyup="word.innerHTML=integerToWords(this.value)" />
<div id="word"></div>

TypeScript Version Based on ES2022 + Fastest
Test on Typescript Playground
Hindi Version
class N2WHindi {
private static readonly zeroTo99: string[] =
'|एक|दो|तीन|चार|पाँच|छः|सात|आठ|नौ|दश|ग्यारह|बारह|तेरह|चौदह|पन्द्रह|सोलह|सत्रह|अठारह|उन्नीस|बीस|इक्कीस|बाईस|तेईस|चौबीस|पच्चीस|छब्बीस|सत्ताईस|अट्ठाईस|उनतीस|तीस|इकतीस|बत्तीस|तैंतीस|चौंतीस|पैंतीस|छत्तीस|सैंतीस|अड़तीस|उनतालीस|चालीस|इकतालीस|बयालीस|तैंतालीस|चौवालीस|पैंतालीस|छियालीस|सैंतालीस|अड़तालीस|उनचास|पचास|इक्यावन|बावन|तिरपन|चौवन|पचपन|छप्पन|सत्तावन|अट्ठावन|उनसठ|साठ|इकसठ|बासठ|तिरसठ|चौंसठ|पैंसठ|छियासठ|सड़सठ|अड़सठ|उनहत्तर|सत्तर|इकहत्तर|बहत्तर|तिहत्तर|चौहत्तर|पचहत्तर|छिहत्तर|सतहत्तर|अठहत्तर|उन्यासी|अस्सी|इक्यासी|बयासी|तिरासी|चौरासी|पचासी|छियासी|सत्तासी|अट्ठासी|नवासी|नब्बे|इक्यानबे|बानबे|तिरानबे|चौरानबे|पंचानबे|छियानबे|सत्तानबे|अट्ठानबे|निन्यान्बे'.split(
'|'
);
private static readonly place: string[] = 'हज़ार|लाख|करोड़|अरब|खरब|नील'.split('|');
public static convert(x: string): string {
let n: number = x.length;
x = n === 0 ? '00' : n === 1 || n % 2 === 0 ? '0' + x : x;
n = x.length;
let r: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n > 0) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' सौ' + (r ? ' ' + r : '');
}
for (let i = 0; n > 0; i++) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WHindi.place[i] + (r ? ' ' + r : '');
}
return r || 'शून्य';
}
}
Indian English Version
class N2WIndian {
private static readonly zeroTo99: string[] = [];
private static readonly place: string[] = 'Thousand|Lakh|Crore|Arab|Kharab|Nil'.split('|');
static {
const ones: string[] =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens: string[] = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t: number = Math.floor(i / 10);
const o: number = i % 10;
N2WIndian.zeroTo99.push(t < 2 ? ones[i] : tens[t] + (o ? ' ' + ones[o] : ''));
}
}
public static convert(x: string): string {
let n: number = x.length;
x = n === 0 ? '00' : n === 1 || n % 2 === 0 ? '0' + x : x;
n = x.length;
let r = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n >= 1) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' Hundred' + (r ? ' ' + r : '');
}
for (let i = 0; n > 0; i++) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WIndian.place[i] + (r ? ' ' + r : '');
}
return r || 'Zero';
}
}
International Version
class N2WIntl {
private static readonly zeroTo999: string[] = [];
private static readonly place =
'|Thousand|Million|Billion|Trillion|Quadrillion|Quintillion|Sextillion|Septillion|Octillion|Nonillion|Decillion|Undecillion|Duodecillion|Tredecillion|Quattuordecillion|Quindecillion|Sedecillion|Septendecillion|Octodecillion|Novendecillion|Vigintillion|Unvigintillion|Duovigintillion|Tresvigintillion|Quattuorvigintillion|Quinvigintillion|Sesvigintillion|Septemvigintillion|Octovigintillion|Novemvigintillion|Trigintillion|Untrigintillion|Duotrigintillion|Trestrigintillion|Quattuortrigintillion|Quintrigintillion|Sestrigintillion|Septentrigintillion|Octotrigintillion|Noventrigintillion|Quadragintillion'.split(
'|'
);
static {
const ones =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t = Math.floor(i / 10);
const o = i % 10;
N2WIntl.zeroTo999[i] = t < 2 ? ones[i] : tens[t] + (o === 0 ? '' : ' ' + ones[o]);
}
for (let i = 100; i < 1000; i++) {
const h = Math.floor(i / 100);
const t = Math.floor(i / 10) % 10;
const o = i % 10;
const r = N2WIntl.zeroTo999[h] + ' Hundred';
N2WIntl.zeroTo999[i] = t === 0 && o === 0 ? r : r + ' ' + N2WIntl.zeroTo999[t * 10 + o];
}
}
public static convert(x: string): string {
let n = x.length;
x = n === 0 ? '000' : (n % 3 === 1 ? '00' : n % 3 === 2 ? '0' : '') + x;
n = x.length;
let r = '';
for (let i = 0; n > 0; i++) {
const v: string =
N2WIntl.zeroTo999[
x.charCodeAt((n -= 3)) * 100 + x.charCodeAt(n + 1) * 10 + x.charCodeAt(n + 2) - 5328
];
if (v) r = v + (i ? ' ' + N2WIntl.place[i] : '') + (r ? ' ' + r : '');
}
return r || 'Zero';
}
}
const test = () => {
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WHindi.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WHindi.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIndian.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WIndian.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIntl.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^126 -1 :\n' + '9'.repeat(126) + '\n' + N2WIntl.convert('9'.repeat(126)));
}
};
test();
Example
N2WHindi.convert('122356')
'एक लाख बाईस हज़ार तीन सौ छप्पन'
N2WIndian.convert('122356')
'One Lakh Twenty Two Thousand Three Hundred Fifty Six'
N2WIntl.convert('122356')
'One Hundred Twenty Two Thousand Three Hundred Fifty Six'
Example to convert currency
const [r, p] = "23.54".split('.');
`${N2WHindi.convert(r)} रुपया और ${N2WHindi.convert(p)} पैसा`
'तेईस रुपया और चौवन पैसा'
`${N2WIndian.convert(r)} Rupees and ${N2WIndian.convert(p)} Paisa`
'Twenty Three Rupees and Fifty Four Paisa'
`${N2WIntl.convert(r)} Dollars and ${N2WIntl.convert(p)} Cents`
'Twenty Three Dollars and Fifty Four Cents'

Converting the input string into a number rather than keeping it as a string, limits the solution to the maximum allowed float / integer value on that machine/browser. My script below handles currency up to 1 Trillion dollars - 1 cent :-). I can be extended to handle up to 999 Trillions by adding 3 or 4 lines of code.
var ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight",
"Nine","Ten","Eleven","Twelve","Thirteen","Fourteen",
"Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"];
var tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
"Eighty","Ninety"];
function words999(n999) { // n999 is an integer less than or equal to 999.
//
// Accept any 3 digit int incl 000 & 999 and return words.
//
var words = ''; var Hn = 0; var n99 = 0;
Hn = Math.floor(n999 / 100); // # of hundreds in it
if (Hn > 0) { // if at least one 100
words = words99(Hn) + " Hundred"; // one call for hundreds
}
n99 = n999 - (Hn * 100); // subtract the hundreds.
words += ((words == '')?'':' ') + words99(n99); // combine the hundreds with tens & ones.
return words;
} // function words999( n999 )
function words99(n99) { // n99 is an integer less than or equal to 99.
//
// Accept any 2 digit int incl 00 & 99 and return words.
//
var words = ''; var Dn = 0; var Un = 0;
Dn = Math.floor(n99 / 10); // # of tens
Un = n99 % 10; // units
if (Dn > 0 || Un > 0) {
if (Dn < 2) {
words += ones[Dn * 10 + Un]; // words for a # < 20
} else {
words += tens[Dn];
if (Un > 0) words += "-" + ones[Un];
}
} // if ( Dn > 0 || Un > 0 )
return words;
} // function words99( n99 )
function getAmtInWords(id1, id2) { // use numeric value of id1 to populate text in id2
//
// Read numeric amount field and convert into word amount
//
var t1 = document.getElementById(id1).value;
var t2 = t1.trim();
amtStr = t2.replace(/,/g,''); // $123,456,789.12 = 123456789.12
dotPos = amtStr.indexOf('.'); // position of dot before cents, -ve if it doesn't exist.
if (dotPos > 0) {
dollars = amtStr.slice(0,dotPos); // 1234.56 = 1234
cents = amtStr.slice(dotPos+1); // 1234.56 = .56
} else if (dotPos == 0) {
dollars = '0';
cents = amtStr.slice(dotPos+1); // 1234.56 = .56
} else {
dollars = amtStr.slice(0); // 1234 = 1234
cents = '0';
}
t1 = '000000000000' + dollars; // to extend to trillion, use 15 zeros
dollars = t1.slice(-12); // and -15 here.
billions = Number(dollars.substr(0,3));
millions = Number(dollars.substr(3,3));
thousands = Number(dollars.substr(6,3));
hundreds = Number(dollars.substr(9,3));
t1 = words999(billions); bW = t1.trim(); // Billions in words
t1 = words999(millions); mW = t1.trim(); // Millions in words
t1 = words999(thousands); tW = t1.trim(); // Thousands in words
t1 = words999(hundreds); hW = t1.trim(); // Hundreds in words
t1 = words99(cents); cW = t1.trim(); // Cents in words
var totAmt = '';
if (bW != '') totAmt += ((totAmt != '') ? ' ' : '') + bW + ' Billion';
if (mW != '') totAmt += ((totAmt != '') ? ' ' : '') + mW + ' Million';
if (tW != '') totAmt += ((totAmt != '') ? ' ' : '') + tW + ' Thousand';
if (hW != '') totAmt += ((totAmt != '') ? ' ' : '') + hW + ' Dollars';
if (cW != '') totAmt += ((totAmt != '') ? ' and ' : '') + cW + ' Cents';
// alert('totAmt = ' + totAmt); // display words in a alert
t1 = document.getElementById(id2).value;
t2 = t1.trim();
if (t2 == '') document.getElementById(id2).value = totAmt;
return false;
} // function getAmtInWords( id1, id2 )
// ======================== [ End Code ] ====================================

If you need with Cent then you may use this one
<script>
var iWords = ['zero', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine'];
var ePlace = ['ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen'];
var tensPlace = ['', ' ten', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety'];
var inWords = [];
var numReversed, inWords, actnumber, i, j;
function tensComplication() {
if (actnumber[i] == 0) {
inWords[j] = '';
} else if (actnumber[i] == 1) {
inWords[j] = ePlace[actnumber[i - 1]];
} else {
inWords[j] = tensPlace[actnumber[i]];
}
}
function convertAmount() {
var numericValue = document.getElementById('bdt').value;
numericValue = parseFloat(numericValue).toFixed(2);
var amount = numericValue.toString().split('.');
var taka = amount[0];
var paisa = amount[1];
document.getElementById('container').innerHTML = convert(taka) +" taka and "+ convert(paisa)+" paisa only";
}
function convert(numericValue) {
inWords = []
if(numericValue == "00" || numericValue =="0"){
return 'zero';
}
var obStr = numericValue.toString();
numReversed = obStr.split('');
actnumber = numReversed.reverse();
if (Number(numericValue) == 0) {
document.getElementById('container').innerHTML = 'BDT Zero';
return false;
}
var iWordsLength = numReversed.length;
var finalWord = '';
j = 0;
for (i = 0; i < iWordsLength; i++) {
switch (i) {
case 0:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
inWords[j] = inWords[j] + '';
break;
case 1:
tensComplication();
break;
case 2:
if (actnumber[i] == '0') {
inWords[j] = '';
} else if (actnumber[i - 1] !== '0' && actnumber[i - 2] !== '0') {
inWords[j] = iWords[actnumber[i]] + ' hundred';
} else {
inWords[j] = iWords[actnumber[i]] + ' hundred';
}
break;
case 3:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
if (actnumber[i + 1] !== '0' || actnumber[i] > '0') {
inWords[j] = inWords[j] + ' thousand';
}
break;
case 4:
tensComplication();
break;
case 5:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
if (actnumber[i + 1] !== '0' || actnumber[i] > '0') {
inWords[j] = inWords[j] + ' lakh';
}
break;
case 6:
tensComplication();
break;
case 7:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
inWords[j] = inWords[j] + ' crore';
break;
case 8:
tensComplication();
break;
default:
break;
}
j++;
}
inWords.reverse();
for (i = 0; i < inWords.length; i++) {
finalWord += inWords[i];
}
return finalWord;
}
</script>
<input type="text" name="bdt" id="bdt" />
<input type="button" name="sr1" value="Click Here" onClick="convertAmount()"/>
<div id="container"></div>
js fiddle
Here taka mean USD and paisa mean cent

This is in response to #LordZardeck's comment to #naomik's excellent answer above. Sorry, I would've commented directly but I've never posted before so I don't have the privilege to do so, so I am posting here instead.
Anyhow, I just happened to translate the ES5 version to a more readable form this past weekend so I'm sharing it here. This should be faithful to the original (including the recent edit) and I hope the naming is clear and accurate.
function int_to_words(int) {
if (int === 0) return 'zero';
var ONES = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
var TENS = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
var SCALE = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];
// Return string of first three digits, padded with zeros if needed
function get_first(str) {
return ('000' + str).substr(-3);
}
// Return string of digits with first three digits chopped off
function get_rest(str) {
return str.substr(0, str.length - 3);
}
// Return string of triplet convereted to words
function triplet_to_words(_3rd, _2nd, _1st) {
return (_3rd == '0' ? '' : ONES[_3rd] + ' hundred ') + (_1st == '0' ? TENS[_2nd] : TENS[_2nd] && TENS[_2nd] + '-' || '') + (ONES[_2nd + _1st] || ONES[_1st]);
}
// Add to words, triplet words with scale word
function add_to_words(words, triplet_words, scale_word) {
return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + words : words;
}
function iter(words, i, first, rest) {
if (first == '000' && rest.length === 0) return words;
return iter(add_to_words(words, triplet_to_words(first[0], first[1], first[2]), SCALE[i]), ++i, get_first(rest), get_rest(rest));
}
return iter('', 0, get_first(String(int)), get_rest(String(int)));
}

var inWords = function(totalRent){
//console.log(totalRent);
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
var number = parseFloat(totalRent).toFixed(2).split(".");
var num = parseInt(number[0]);
var digit = parseInt(number[1]);
//console.log(num);
if ((num.toString()).length > 9) return 'overflow';
var n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
var d = ('00' + digit).substr(-2).match(/^(\d{2})$/);;
if (!n) return; var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'Rupee ' : '';
str += (d[1] != 0) ? ((str != '' ) ? "and " : '') + (a[Number(d[1])] || b[d[1][0]] + ' ' + a[d[1][1]]) + 'Paise ' : 'Only!';
console.log(str);
return str;
}
This is modified code supports for Indian Rupee with 2 decimal place.

Below are the translations from
integer to word
float to word
money to word
Test cases are at the bottom
var ONE_THOUSAND = Math.pow(10, 3);
var ONE_MILLION = Math.pow(10, 6);
var ONE_BILLION = Math.pow(10, 9);
var ONE_TRILLION = Math.pow(10, 12);
var ONE_QUADRILLION = Math.pow(10, 15);
var ONE_QUINTILLION = Math.pow(10, 18);
function integerToWord(integer) {
var prefix = '';
var suffix = '';
if (!integer){ return "zero"; }
if(integer < 0){
prefix = "negative";
suffix = integerToWord(-1 * integer);
return prefix + " " + suffix;
}
if(integer <= 90){
switch (integer) {
case integer < 0:
prefix = "negative";
suffix = integerToWord(-1 * integer);
return prefix + " " + suffix;
case 1: return "one";
case 2: return "two";
case 3: return "three";
case 4: return "four";
case 5: return "five";
case 6: return "six";
case 7: return "seven";
case 8: return "eight";
case 9: return "nine";
case 10: return "ten";
case 11: return "eleven";
case 12: return "twelve";
case 13: return "thirteen";
case 14: return "fourteen";
case 15: return "fifteen";
case 16: return "sixteen";
case 17: return "seventeen";
case 18: return "eighteen";
case 19: return "nineteen";
case 20: return "twenty";
case 30: return "thirty";
case 40: return "forty";
case 50: return "fifty";
case 60: return "sixty";
case 70: return "seventy";
case 80: return "eighty";
case 90: return "ninety";
default: break;
}
}
if(integer < 100){
prefix = integerToWord(integer - integer % 10);
suffix = integerToWord(integer % 10);
return prefix + "-" + suffix;
}
if(integer < ONE_THOUSAND){
prefix = integerToWord(parseInt(Math.floor(integer / 100), 10) ) + " hundred";
if (integer % 100){ suffix = " and " + integerToWord(integer % 100); }
return prefix + suffix;
}
if(integer < ONE_MILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_THOUSAND), 10)) + " thousand";
if (integer % ONE_THOUSAND){ suffix = integerToWord(integer % ONE_THOUSAND); }
}
else if(integer < ONE_BILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_MILLION), 10)) + " million";
if (integer % ONE_MILLION){ suffix = integerToWord(integer % ONE_MILLION); }
}
else if(integer < ONE_TRILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_BILLION), 10)) + " billion";
if (integer % ONE_BILLION){ suffix = integerToWord(integer % ONE_BILLION); }
}
else if(integer < ONE_QUADRILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_TRILLION), 10)) + " trillion";
if (integer % ONE_TRILLION){ suffix = integerToWord(integer % ONE_TRILLION); }
}
else if(integer < ONE_QUINTILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_QUADRILLION), 10)) + " quadrillion";
if (integer % ONE_QUADRILLION){ suffix = integerToWord(integer % ONE_QUADRILLION); }
} else {
return '';
}
return prefix + " " + suffix;
}
function moneyToWord(value){
var decimalValue = (value % 1);
var integer = value - decimalValue;
decimalValue = Math.round(decimalValue * 100);
var decimalText = !decimalValue? '': integerToWord(decimalValue) + ' cent' + (decimalValue === 1? '': 's');
var integerText= !integer? '': integerToWord(integer) + ' dollar' + (integer === 1? '': 's');
return (
integer && !decimalValue? integerText:
integer && decimalValue? integerText + ' and ' + decimalText:
!integer && decimalValue? decimalText:
'zero cents'
);
}
function floatToWord(value){
var decimalValue = (value % 1);
var integer = value - decimalValue;
decimalValue = Math.round(decimalValue * 100);
var decimalText = !decimalValue? '':
decimalValue < 10? "point o' " + integerToWord(decimalValue):
decimalValue % 10 === 0? 'point ' + integerToWord(decimalValue / 10):
'point ' + integerToWord(decimalValue);
return (
integer && !decimalValue? integerToWord(integer):
integer && decimalValue? [integerToWord(integer), decimalText].join(' '):
!integer && decimalValue? decimalText:
integerToWord(0)
);
}
// test
(function(){
console.log('integerToWord ==================================');
for(var i = 0; i < 101; ++i){
console.log('%s=%s', i, integerToWord(i));
}
console.log('floatToWord ====================================');
i = 131;
while(i--){
console.log('%s=%s', i / 100, floatToWord(i / 100));
}
console.log('moneyToWord ====================================');
for(i = 0; i < 131; ++i){
console.log('%s=%s', i / 100, moneyToWord(i / 100));
}
}());

Another conversion that uses remainders and supports different languages:
function numberToWords(number) {
var result = [];
var fraction = number.toFixed(2).split('.');
var integer_part = parseInt(fraction[0]);
// var fractional_part = parseInt(fraction[1]); -- not handled here
var previousNumber = null;
for (var i = 0; i < fraction[0].length; i++) {
var reminder = Math.floor(integer_part % 10);
integer_part /= 10;
var name = getNumberName(reminder, i, fraction[0].length, previousNumber);
previousNumber = reminder;
if (name)
result.push(name);
}
result.reverse();
return result.join(' ');
}
The getNumberName function is language-dependent and handles numbers up to 9999 (but it is easy to extend it to handle larger numbers):
function getNumberName(number, power, places, previousNumber) {
var result = "";
if (power == 1) {
result = handleTeensAndTys(number, previousNumber);
} else if (power == 0 && places != 1 || number == 0) {
// skip number that was handled in teens and zero
} else {
result = locale.numberNames[number.toString()] + locale.powerNames[power.toString()];
}
return result;
}
handleTeensAndTys handles multiples of ten:
function handleTeensAndTys(number, previousNumber) {
var result = "";
if (number == 1) { // teens
if (previousNumber in locale.specialTeenNames) {
result = locale.specialTeenNames[previousNumber];
} else if (previousNumber in locale.specialTyNames) {
result = locale.specialTyNames[previousNumber] + locale.teenSuffix;
} else {
result = locale.numberNames[previousNumber] + locale.teenSuffix;
}
} else if (number == 0) { // previousNumber was not handled in teens
result = locale.numberNames[previousNumber.toString()];
} else { // other tys
if (number in locale.specialTyNames) {
result = locale.specialTyNames[number];
} else {
result = locale.numberNames[number];
}
result += locale.powerNames[1];
if (previousNumber != 0) {
result += " " + locale.numberNames[previousNumber.toString()];
}
}
return result;
}
Finally, locale examples:
var locale = { // English
numberNames: {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine" },
powerNames: {0: "", 1: "ty", 2: " hundred", 3: " thousand" },
specialTeenNames: {0: "ten", 1: "eleven", 2: "twelve" },
specialTyNames: {2: "twen", 3: "thir", 5: "fif" },
teenSuffix: "teen"
};
var locale = { // Estonian
numberNames: {1: "üks", 2: "kaks", 3: "kolm", 4: "neli", 5: "viis", 6: "kuus", 7: "seitse", 8: "kaheksa", 9: "üheksa"},
powerNames: {0: "", 1: "kümmend", 2: "sada", 3: " tuhat" },
specialTeenNames: {0: "kümme"},
specialTyNames: {},
teenSuffix: "teist"
};
Here's a JSFiddle with tests: https://jsfiddle.net/rcrxna7v/15/

Function that will work with decimal values also
function amountToWords(amountInDigits){
// American Numbering System
var th = ['','thousand','million', 'billion','trillion'];
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function toWords(s){
s = s.toString();
s = s.replace(/[\, ]/g,'');
if (s != parseFloat(s))
return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i=0; i < x; i++){
if ((x-i)%3==2){
if (n[i] == '1') {
str += tn[Number(n[i+1])] + ' ';
i++; sk=1;
} else if (n[i]!=0) {
str += tw[n[i]-2] + ' ';sk=1;
}
} else if (n[i]!=0) {
str += dg[n[i]] +' ';
if ((x-i)%3==0)
str += 'hundred ';
sk=1;
} if ((x-i)%3==1) {
if (sk) str += th[(x-i-1)/3] + ' ';sk=0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';
}
return str.replace(/\s+/g,' ');
}
return toWords(amountInDigits);
}
<input type="text" name="number" placeholder="Number OR Amount" onkeyup="word.innerHTML=amountToWords(this.value)" />
<div id="word"></div>

I modified #McShaman's code, converted it to CoffeeScript, and added docs via JSNice. Here's the result, for those interested (English):
###
Convert an integer to an English string equivalent
#param {Integer} number the integer to be converted
#return {String} the English number equivalent
###
inWords = (number) ->
###
#property {Array}
###
englishIntegers = [
""
"one "
"two "
"three "
"four "
"five "
"six "
"seven "
"eight "
"nine "
"ten "
"eleven "
"twelve "
"thirteen "
"fourteen "
"fifteen "
"sixteen "
"seventeen "
"eighteen "
"nineteen "
]
###
#property {Array}
###
englishIntegerTens = [
""
""
"twenty"
"thirty"
"forty"
"fifty"
"sixty"
"seventy"
"eighty"
"ninety"
]
###
#property {Array}
###
englishIntegerThousands = [
"thousand"
"million"
""
]
number = number.toString()
return "" if number.length > 9
###
#property {string}
###
number = ("000000000" + number).substr(-9)
###
#property {(Array.<string>|null)}
###
number = number.match(/.{3}/g)
###
#property {string}
###
convertedWords = ""
###
#property {number}
###
i = 0
while i < englishIntegerThousands.length
###
#property {string}
###
currentNumber = number[i]
###
#property {string}
###
tempResult = ""
tempResult += (if convertedWords isnt "" then " " + englishIntegerThousands[i] + " " else "")
tempResult += (if currentNumber[0] isnt 0 then englishIntegers[Number(currentNumber[0])] + "hundred " else "")
###
#property {string}
###
currentNumber = currentNumber.substr(1)
tempResult += (if currentNumber isnt 0 then ((if tempResult isnt "" then "and " else "")) + (englishIntegers[Number(currentNumber)] or englishIntegerTens[currentNumber[0]] + " " + englishIntegers[currentNumber[1]]) else "")
convertedWords += tempResult
i++
convertedWords

Though, this question has been answered - still I want to share something I recently developed in java script (based on the logic of an old C#. Net implementation I found in Internet) for converting Indian currency values to Words. It can handle up to 40 digits. You can have a look.
Usage:
InrToWordConverter.Initialize();.
var inWords = InrToWordConverter.ConvertToWord(amount);
Implementation:
htPunctuation = {};
listStaticSuffix = {};
listStaticPrefix = {};
listHelpNotation = {};
var InrToWordConverter = function () {
};
InrToWordConverter.Initialize = function () {
InrToWordConverter.LoadStaticPrefix();
InrToWordConverter.LoadStaticSuffix();
InrToWordConverter.LoadHelpofNotation();
};
InrToWordConverter.ConvertToWord = function (value) {
value = value.toString();
if (value) {
var tokens = value.split(".");
var rsPart = "";
var psPart = "";
if (tokens.length === 2) {
rsPart = String.trim(tokens[0]) || "0";
psPart = String.trim(tokens[1]) || "0";
}
else if (tokens.length === 1) {
rsPart = String.trim(tokens[0]) || "0";
psPart = "0";
}
else {
rsPart = "0";
psPart = "0";
}
htPunctuation = {};
var rsInWords = InrToWordConverter.ConvertToWordInternal(rsPart) || "Zero";
var psInWords = InrToWordConverter.ConvertToWordInternal(psPart) || "Zero";
var result = "Rupees " + rsInWords + "and " + psInWords + " Paise.";
return result;
}
};
InrToWordConverter.ConvertToWordInternal = function (value) {
var convertedString = "";
if (!(value.toString().length > 40))
{
if (InrToWordConverter.IsNumeric(value.toString()))
{
try
{
var strValue = InrToWordConverter.Reverse(value);
switch (strValue.length)
{
case 1:
if (parseInt(strValue.toString()) > 0) {
convertedString = InrToWordConverter.GetWordConversion(value);
}
else {
convertedString = "Zero ";
}
break;
case 2:
convertedString = InrToWordConverter.GetWordConversion(value);
break;
default:
InrToWordConverter.InsertToPunctuationTable(strValue);
InrToWordConverter.ReverseHashTable();
convertedString = InrToWordConverter.ReturnHashtableValue();
break;
}
}
catch (exception) {
convertedString = "Unexpected Error Occured <br/>";
}
}
else {
convertedString = "Please Enter Numbers Only, Decimal Values Are not supported";
}
}
else {
convertedString = "Please Enter Value in Less Then or Equal to 40 Digit";
}
return convertedString;
};
InrToWordConverter.IsNumeric = function (valueInNumeric) {
var isFine = true;
valueInNumeric = valueInNumeric || "";
var len = valueInNumeric.length;
for (var i = 0; i < len; i++) {
var ch = valueInNumeric[i];
if (!(ch >= '0' && ch <= '9')) {
isFine = false;
break;
}
}
return isFine;
};
InrToWordConverter.ReturnHashtableValue = function () {
var strFinalString = "";
var keysArr = [];
for (var key in htPunctuation) {
keysArr.push(key);
}
for (var i = keysArr.length - 1; i >= 0; i--) {
var hKey = keysArr[i];
if (InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) !== "") {
strFinalString = strFinalString + InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) + InrToWordConverter.StaticPrefixFind((hKey).toString());
}
}
return strFinalString;
};
InrToWordConverter.ReverseHashTable = function () {
var htTemp = {};
for (var key in htPunctuation) {
var item = htPunctuation[key];
htTemp[key] = InrToWordConverter.Reverse(item.toString());
}
htPunctuation = {};
htPunctuation = htTemp;
};
InrToWordConverter.InsertToPunctuationTable = function (strValue) {
htPunctuation[1] = strValue.substr(0, 3).toString();
var j = 2;
for (var i = 3; i < strValue.length; i = i + 2) {
if (strValue.substr(i).length > 0) {
if (strValue.substr(i).length >= 2) {
htPunctuation[j] = strValue.substr(i, 2).toString();
}
else {
htPunctuation[j] = strValue.substr(i, 1).toString();
}
}
else {
break;
}
j++;
}
};
InrToWordConverter.Reverse = function (strValue) {
var reversed = "";
for (var i in strValue) {
var ch = strValue[i];
reversed = ch + reversed;
}
return reversed;
};
InrToWordConverter.GetWordConversion = function (inputNumber) {
var toReturnWord = "";
if (inputNumber.length <= 3 && inputNumber.length > 0) {
if (inputNumber.length === 3) {
if (parseInt(inputNumber.substr(0, 1)) > 0) {
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1)) + "Hundred ";
}
var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 2));
if (tempString === "")
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1) + "0");
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(2, 1));
}
toReturnWord = toReturnWord + tempString;
}
if (inputNumber.length === 2)
{
var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 2));
if (tempString === "")
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1) + "0");
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1));
}
toReturnWord = toReturnWord + tempString;
}
if (inputNumber.length === 1)
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1));
}
}
return toReturnWord;
};
InrToWordConverter.StaticSuffixFind = function (numberKey) {
var valueFromNumber = "";
for (var key in listStaticSuffix) {
if (String.trim(key.toString()) === String.trim(numberKey)) {
valueFromNumber = listStaticSuffix[key].toString();
break;
}
}
return valueFromNumber;
};
InrToWordConverter.StaticPrefixFind = function (numberKey) {
var valueFromNumber = "";
for (var key in listStaticPrefix) {
if (String.trim(key) === String.trim(numberKey)) {
valueFromNumber = listStaticPrefix[key].toString();
break;
}
}
return valueFromNumber;
};
InrToWordConverter.StaticHelpNotationFind = function (numberKey) {
var helpText = "";
for (var key in listHelpNotation) {
if (String.trim(key.toString()) === String.trim(numberKey)) {
helpText = listHelpNotation[key].toString();
break;
}
}
return helpText;
};
InrToWordConverter.LoadStaticPrefix = function () {
listStaticPrefix[2] = "Thousand ";
listStaticPrefix[3] = "Lac ";
listStaticPrefix[4] = "Crore ";
listStaticPrefix[5] = "Arab ";
listStaticPrefix[6] = "Kharab ";
listStaticPrefix[7] = "Neel ";
listStaticPrefix[8] = "Padma ";
listStaticPrefix[9] = "Shankh ";
listStaticPrefix[10] = "Maha-shankh ";
listStaticPrefix[11] = "Ank ";
listStaticPrefix[12] = "Jald ";
listStaticPrefix[13] = "Madh ";
listStaticPrefix[14] = "Paraardha ";
listStaticPrefix[15] = "Ant ";
listStaticPrefix[16] = "Maha-ant ";
listStaticPrefix[17] = "Shisht ";
listStaticPrefix[18] = "Singhar ";
listStaticPrefix[19] = "Maha-singhar ";
listStaticPrefix[20] = "Adant-singhar ";
};
InrToWordConverter.LoadStaticSuffix = function () {
listStaticSuffix[1] = "One ";
listStaticSuffix[2] = "Two ";
listStaticSuffix[3] = "Three ";
listStaticSuffix[4] = "Four ";
listStaticSuffix[5] = "Five ";
listStaticSuffix[6] = "Six ";
listStaticSuffix[7] = "Seven ";
listStaticSuffix[8] = "Eight ";
listStaticSuffix[9] = "Nine ";
listStaticSuffix[10] = "Ten ";
listStaticSuffix[11] = "Eleven ";
listStaticSuffix[12] = "Twelve ";
listStaticSuffix[13] = "Thirteen ";
listStaticSuffix[14] = "Fourteen ";
listStaticSuffix[15] = "Fifteen ";
listStaticSuffix[16] = "Sixteen ";
listStaticSuffix[17] = "Seventeen ";
listStaticSuffix[18] = "Eighteen ";
listStaticSuffix[19] = "Nineteen ";
listStaticSuffix[20] = "Twenty ";
listStaticSuffix[30] = "Thirty ";
listStaticSuffix[40] = "Fourty ";
listStaticSuffix[50] = "Fifty ";
listStaticSuffix[60] = "Sixty ";
listStaticSuffix[70] = "Seventy ";
listStaticSuffix[80] = "Eighty ";
listStaticSuffix[90] = "Ninty ";
};
InrToWordConverter.LoadHelpofNotation = function () {
listHelpNotation[2] = "=1,000 (3 Trailing Zeros)";
listHelpNotation[3] = "=1,00,000 (5 Trailing Zeros)";
listHelpNotation[4] = "=1,00,00,000 (7 Trailing Zeros)";
listHelpNotation[5] = "=1,00,00,00,000 (9 Trailing Zeros)";
listHelpNotation[6] = "=1,00,00,00,00,000 (11 Trailing Zeros)";
listHelpNotation[7] = "=1,00,00,00,00,00,000 (13 Trailing Zeros)";
listHelpNotation[8] = "=1,00,00,00,00,00,00,000 (15 Trailing Zeros)";
listHelpNotation[9] = "=1,00,00,00,00,00,00,00,000 (17 Trailing Zeros)";
listHelpNotation[10] = "=1,00,00,00,00,00,00,00,00,000 (19 Trailing Zeros)";
listHelpNotation[11] = "=1,00,00,00,00,00,00,00,00,00,000 (21 Trailing Zeros)";
listHelpNotation[12] = "=1,00,00,00,00,00,00,00,00,00,00,000 (23 Trailing Zeros)";
listHelpNotation[13] = "=1,00,00,00,00,00,00,00,00,00,00,00,000 (25 Trailing Zeros)";
listHelpNotation[14] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,000 (27 Trailing Zeros)";
listHelpNotation[15] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (29 Trailing Zeros)";
listHelpNotation[16] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (31 Trailing Zeros)";
listHelpNotation[17] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (33 Trailing Zeros)";
listHelpNotation[18] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (35 Trailing Zeros)";
listHelpNotation[19] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (37 Trailing Zeros)";
listHelpNotation[20] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (39 Trailing Zeros)";
};
if (!String.trim) {
String.trim = function (str) {
var result = "";
var firstNonWhiteSpaceFound = false;
var startIndex = -1;
var endIndex = -1;
if (str) {
for (var i = 0; i < str.length; i++) {
if (firstNonWhiteSpaceFound === false) {
if (str[i] === ' ' || str[i] === '\t') {
continue;
}
else {
firstNonWhiteSpaceFound = true;
startIndex = i;
endIndex = i;
}
}
else {
if (str[i] === ' ' || str[i] === '\t') {
continue;
}
else {
endIndex = i;
}
}
}
if (startIndex !== -1 && endIndex !== -1) {
result = str.slice(startIndex, endIndex + 1);
}
}
return result;
};
}

Try this code with a Turkish currency compliant JavaScript
function dene() {
var inpt = document.getElementById("tar1").value;
var spt = inpt.split('');
spt.reverse();
var tek = ["", "Bir", "İki", "Üç", "Dört", "Beş", "Altı", "Yedi", "Sekiz", "Dokuz"];
var onlu = ["", "On", "Yirmi", "Otuz", "Kırk", "Elli", "Atmış", "Yetmiş", "Seksen", "Doksan"];
var Yuz = ["", "Yüz", "İkiYüz", "Üçyüz", "DörtYüz", "BeşYüz", "AltıYüz", "YediYüz", "SekizYüz", "DokuzYüz"];
var ska = ["", "", "", "", "Bin", "Milyon", "Milyar", "Trilyon", "Katrilyon", "Kentilyon"];
var i, j;
var bas3 = "";
var bas6 = "";
var bas9 = "";
var bas12 = "";
var total;
for(i = 0; i < 1; i++) {
bas3 += Yuz[spt[i+2]] + onlu[spt[i+1]] + tek[spt[i]];
bas6 += Yuz[spt[i+5]] + onlu[spt[i+4]] + tek[spt[i+3]] + ska[4];
bas9 += Yuz[spt[i+8]] + onlu[spt[i+7]] + tek[spt[i+6]] + ska[5];
bas12 += Yuz[spt[i+11]] + onlu[spt[i+10]] + tek[spt[i+9]] + ska[6];
if(inpt.length < 4) {
bas6 = '';
bas9 = '';
}
if(inpt.length > 6 && inpt.slice(5, 6) == 0) {
bas6 = bas6.replace(/Bin/g, '');
}
if(inpt.length < 7) {
bas9 = '';
}
if(inpt.length > 9 && inpt.slice(1,3) == 000){
bas9 = bas9.replace(/Milyon/g, '');
}
if(inpt.length < 10) {
bas12 = '';
}
}
total = bas12 + bas9 + bas6 + bas3;
total = total.replace(NaN, '');
total = total.replace(undefined, '');
document.getElementById('demo').innerHTML =
total;
}

Lot of good answers. I needed mine for Indian (South Asian) numbering system. I modified one of the codes above - attaching it here, in case, someone else needs this. In the Indian numbering system, groups after thousands are in in 2 digits, not 3 as in the western system.
var IS_SOUTH_ASIAN = true;
function int_to_words(int) {
if (int === 0) return 'zero';
var ONES_WORD = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
var TENS_WORD = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
var SCALE_WORD_WESTERN = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];
var SCALE_WORD_SOUTH_ASIAN = ['','thousand','lakh','crore','arab','kharab','neel','padma','shankh','***','***'];
var GROUP_SIZE = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? 2 : 3;
var SCALE_WORD = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? SCALE_WORD_SOUTH_ASIAN : SCALE_WORD_WESTERN;
// Return string of first three digits, padded with zeros if needed
function get_first_3(str) {
return ('000' + str).substr(-(3));
}
function get_first(str) { //-- Return string of first GROUP_SIZE digits, padded with zeros if needed, if group size is 2, make it size 3 by prefixing with a '0'
return (GROUP_SIZE == 2 ? '0' : '') + ('000' + str).substr(-(GROUP_SIZE));
}
// Return string of digits with first three digits chopped off
function get_rest_3(str) {
return str.substr(0, str.length - 3);
}
function get_rest(str) { // Return string of digits with first GROUP_SIZE digits chopped off
return str.substr(0, str.length - GROUP_SIZE);
}
// Return string of triplet convereted to words
function triplet_to_words(_3rd, _2nd, _1st) {
return (_3rd == '0' ? '' : ONES_WORD[_3rd] + ' hundred ') +
(_1st == '0' ? TENS_WORD[_2nd] : TENS_WORD[_2nd] && TENS_WORD[_2nd] + '-' || '') +
(ONES_WORD[_2nd + _1st] || ONES_WORD[_1st]); //-- 1st one returns one-nineteen - second one returns one-nine
}
// Add to result, triplet words with scale word
function add_to_result(result, triplet_words, scale_word) {
return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + result : result;
}
function recurse (result, scaleIdx, first, rest) {
if (first == '000' && rest.length === 0) return result;
var newResult = add_to_result (result, triplet_to_words (first[0], first[1], first[2]), SCALE_WORD[scaleIdx]);
return recurse (newResult, ++scaleIdx, get_first(rest), get_rest(rest));
}
return recurse ('', 0, get_first_3(String(int)), get_rest_3(String(int)));
}

while this system does use a for loop, It uses US english and is fast, accurate, and expandable(you can add infinite values to the "th" var and they will be included).
This function grabs the 3 groups of numbers backwards so it can get the number groups where a , would normally separate them in the numeric form. Then each group of three numbers is added to an array with the word form of just the 3 numbers(ex: one hundred twenty three). It then takes that new array list, and reverses it again, while adding the th var of the same index to the end of the string.
var ones = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var tens = ['', '', 'twenty ','thirty ','forty ','fifty ', 'sixty ','seventy ','eighty ','ninety ', 'hundred '];
var th = ['', 'thousand ','million ','billion ', 'trillion '];
function numberToWord(number){
var text = "";
var size = number.length;
var textList = [];
var textListCount = 0;
//get each 3 digit numbers
for(var i = number.length-1; i >= 0; i -= 3){
//get 3 digit group
var num = 0;
if(number[(i-2)]){num += number[(i-2)];}
if(number[(i-1)]){num += number[(i-1)];}
if(number[i]){num += number[i];}
//remove any extra 0's from begining of number
num = Math.floor(num).toString();
if(num.length == 1 || num < 20){
//if one digit or less than 20
textList[textListCount] = ones[num];
}else if(num.length == 2){
//if 2 digits and greater than 20
textList[textListCount] = tens[num[0]]+ones[num[1]];
}else if(num.length == 3){
//if 3 digits
textList[textListCount] = ones[num[0]]+tens[10]+tens[num[1]]+ones[num[2]];
}
textListCount++;
}
//add the list of 3 digit groups to the string
for(var i = textList.length-1; i >= 0; i--){
if(textList[i] !== ''){text += textList[i]+th[i];} //skip if the number was 0
}
return text;
}

This is also in response to naomik's excellent post! Unfortunately I don't have the rep to post in the correct place but I leave this here in case it can help anyone.
If you need British English written form you need to make some adaptions to the code. British English differs from the American in a couple of ways. Basically you need to insert the word 'and' in two specific places.
After a hundred assuming there are tens and ones. E.g One hundred and ten. One thousand and seventeen. NOT One thousand one hundred and.
In certain edges, after a thousand, a million, a billion etc. when there are no smaller units. E.g. One thousand and ten. One million and forty four. NOT One million and one thousand.
The first situation can be addressed by checking for 10s and 1s in the makeGroup method and appending 'and' when they exist.
makeGroup = ([ones,tens,huns]) => {
var adjective = this.num(ones) ? ' hundred and ' : this.num(tens) ? ' hundred and ' : ' hundred';
return [
this.num(huns) === 0 ? '' : this.a[huns] + adjective,
this.num(ones) === 0 ? this.b[tens] : this.b[tens] && this.b[tens] + '-' || '',
this.a[tens+ones] || this.a[ones]
].join('');
};
The second case is more complicated. It is equivalent to
add 'and' to 'a million, a thousand', or 'a billion' if the antepenultimate number is zero. e.g.
1,100,057 one million one hundred thousand and fifty seven.
5,000,006 five million and six
I think this could be implemented in #naomik's code through the use of a filter function but I wasn't able to work out how. In the end I settled on hackily looping through the returned array of words and using indexOf to look for instances where the word 'hundred' was missing from the final element.

I've just written paisa.js to do this, and it handles lakhs and crores correctly as well, can check it out. The core looks a bit like this:
const regulars = [
{
1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'
},
{
2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'
}
]
const exceptions = {
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen'
}
const partInWords = (part) => {
if (parseInt(part) === 0) return
const digits = part.split('')
const words = []
if (digits.length === 3) {
words.push([regulars[0][digits.shift()], 'hundred'].join(' '))
}
if (exceptions[digits.join('')]) {
words.push(exceptions[digits.join('')])
} else {
words.push(digits.reverse().reduce((memo, el, i) => {
memo.unshift(regulars[i][el])
return memo
}, []).filter(w => w).join(' '))
}
return words.filter(w => w.trim().length).join(' and ')
}

My solution is based on Juan Gaitán's solution for Indian currency, works up to crores.
function valueInWords(value) {
let ones = ['', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
let tens = ['twenty','thirty', 'forty','fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
let digit = 0;
if (value < 20) return ones[value];
if (value < 100) {
digit = value % 10; //remainder
return tens[Math.floor(value/10)-2] + " " + (digit > 0 ? ones[digit] : "");
}
if (value < 1000) {
return ones[Math.floor(value/100)] + " hundred " + (value % 100 > 0 ? valueInWords(value % 100) : "");
}
if (value < 100000) {
return valueInWords(Math.floor(value/1000)) + " thousand " + (value % 1000 > 0 ? valueInWords(value % 1000) : "");
}
if (value < 10000000) {
return valueInWords(Math.floor(value/100000)) + " lakh " + (value % 100000 > 0 ? valueInWords(value % 100000) : "");
}
return valueInWords(Math.floor(value/10000000)) + " crore " + (value % 10000000 > 0 ? valueInWords(value % 10000000) : "");
}

function numberToEnglish( n ) {
var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g,"");
/* Is number zero? */
if( parseInt( string ) === 0 ) {
return 'zero';
}
/* Array of units as words */
units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
/* Array of tens as words */
tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
/* Array of scales as words */
scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
/* Split user argument into 3 digit chunks from right to left */
start = string.length;
chunks = [];
while( start > 0 ) {
end = start;
chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
}
/* Check if function has enough scale words to be able to stringify the user argument */
chunksLen = chunks.length;
if( chunksLen > scales.length ) {
return '';
}
/* Stringify each integer in each chunk */
words = [];
for( i = 0; i < chunksLen; i++ ) {
chunk = parseInt( chunks[i] );
if( chunk ) {
/* Split chunk into array of individual integers */
ints = chunks[i].split( '' ).reverse().map( parseFloat );
/* If tens integer is 1, i.e. 10, then add 10 to units integer */
if( ints[1] === 1 ) {
ints[0] += 10;
}
/* Add scale word if chunk is not zero and array item exists */
if( ( word = scales[i] ) ) {
words.push( word );
}
/* Add unit word if array item exists */
if( ( word = units[ ints[0] ] ) ) {
words.push( word );
}
/* Add tens word if array item exists */
if( ( word = tens[ ints[1] ] ) ) {
words.push( word );
}
/* Add 'and' string after units or tens integer if: */
if( ints[0] || ints[1] ) {
/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
if( ints[2] || ! i && chunksLen ) {
words.push( and );
}
}
/* Add hundreds word if array item exists */
if( ( word = units[ ints[2] ] ) ) {
words.push( word + ' hundred' );
}
}
}
return words.reverse().join( ' ' );
}
// - - - - - Tests - - - - - -
function test(v) {
var sep = ('string'==typeof v)?'"':'';
console.log("numberToEnglish("+sep + v.toString() + sep+") = "+numberToEnglish(v));
}
test(2);
test(721);
test(13463);
test(1000001);
test("21,683,200,000,621,384");

For those who are looking for imperial/english naming conventions.
Based on #Salman's answer
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function inWords (num) {
if ((num = num.toString()).length > 12) return 'overflow';
n = ('00000000000' + num).substr(-12).match(/^(\d{3})(\d{3})(\d{3})(\d{1})(\d{2})$/);
if (!n) return; var str = '';
str += (n[1] != 0) ? (Number(n[1]) > 99 ? this.a[Number(n[1][0])] + 'hundred ' : '') + (a[Number(n[1])] || b[n[1][1]] + ' ' + a[n[1][2]]) + 'billion ' : '';
str += (n[2] != 0) ? (Number(n[2]) > 99 ? this.a[Number(n[2][0])] + 'hundred ' : '') + (a[Number(n[2])] || b[n[2][1]] + ' ' + a[n[2][2]]) + 'million ' : '';
str += (n[3] != 0) ? (Number(n[3]) > 99 ? this.a[Number(n[3][0])] + 'hundred ' : '') + (a[Number(n[3])] || b[n[3][1]] + ' ' + a[n[3][2]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (Number(n[5]) !== 0) ? ((str !== '') ? 'and ' : '') +
(this.a[Number(n[5])] || this.b[n[5][0]] + ' ' +
this.a[n[5][1]]) + '' : '';
return str;
}
document.getElementById('number').onkeyup = function () {
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
<span id="words"></span>
<input id="number" type="text" />

Cleanest and easiest approach that came to mind:
const numberText = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand',
}
const numberValues = Object.keys(numberText)
.map((val) => Number(val))
.sort((a, b) => b - a)
const convertNumberToEnglishText = (n) => {
if (n === 0) return 'zero'
if (n < 0) return 'negative ' + convertNumberToEnglishText(-n)
let num = n
let text = ''
for (const numberValue of numberValues) {
const count = Math.trunc(num / numberValue)
if (count < 1) continue
if (numberValue >= 100) text += convertNumberToEnglishText(count) + ' '
text += numberText[numberValue] + ' '
num -= count * numberValue
}
if (num !== 0) throw Error('Something went wrong!')
return text.trim()
}

Probably the simplest one I got and used was from Ben E. I made modifications to his code since it would only return for example 'Five Hundred' when you try to convert 500,000.00. I just added a line of conditional code to fix it. Also added the provision for giving out the last two decimal places. I'm now using it to convert the amount to words when printing checks. Here was my revision added to it:
if (Math.floor((number%(100*Math.pow(1000,i))/Math.pow(1000,i))) == 0) {
word = first[Math.floor(tempNumber/(100*Math.pow(1000,i)))] + 'Hundred ' + mad[i]
+ ' ' + word;
} else {
I'm having a hard time pasting the code here but let me know if you need any clarifications

answared by #pramod kharade
simplified
function NumToWord(inputNumber) {
var str = new String(inputNumber)
var splt = str.split("");
var rev = splt.reverse();
var once = ['Zero', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'];
var twos = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
var tens = ['', 'Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];
numLength = rev.length;
var word = new Array();
var j = 0;
for (i = 0; i < numLength; i++) {
switch (i) {
case 0:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = '' + once[rev[i]];
}
word[j] = word[j];
break;
case 1:
aboveTens();
break;
case 2:
if (rev[i] == 0) {
word[j] = '';
}
else if ((rev[i - 1] == 0) || (rev[i - 2] == 0)) {
word[j] = once[rev[i]] + " Hundred ";
}
else {
word[j] = once[rev[i]] + " Hundred and";
}
break;
case 3:
if (rev[i] == 0 || rev[i + 1] == 1) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if ((rev[i + 1] != 0) || (rev[i] > 0)) {
word[j] = word[j] + " Thousand";
}
break;
case 4:
aboveTens();
break;
case 5:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if (rev[i + 1] !== '0' || rev[i] > '0') {
word[j] = word[j] + " Lakh";
}
break;
case 6:
aboveTens();
break;
case 7:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if (rev[i + 1] !== '0' || rev[i] > '0') {
word[j] = word[j] + " Crore";
}
break;
case 8:
aboveTens();
break;
default: break;
}
j++;
}
function aboveTens() {
if (rev[i] == 0) { word[j] = ''; }
else if (rev[i] == 1) { word[j] = twos[rev[i - 1]]; }
else { word[j] = tens[rev[i]]; }
}
word.reverse();
var finalOutput = '';
for (i = 0; i < numLength; i++) {
finalOutput = finalOutput + word[i];
}
return finalOutput;
}
console.log(NumToWord(123))
console.log(NumToWord(12345678))
console.log(NumToWord(12334543))
console.log(NumToWord(6789876123))

Convertirlos en Español
class Converter {
constructor() {
this.unit = ['CERO', 'UN', 'DOS', 'TRES', 'CUATRO', 'CINCO', 'SEIS', 'SIETE', 'OCHO', 'NUEVE'];
this.units = ['CERO', 'UNO', 'DOS', 'TRES', 'CUATRO', 'CINCO', 'SEIS', 'SIETE', 'OCHO', 'NUEVE'];
this.tenToSixteen = ['DIEZ', 'ONCE', 'DOCE', 'TRECE', 'CATORCE', 'QUINCE', 'DIECISEIS'];
this.tens = ['TREINTA', 'CUARENTA', 'CINCUENTA', 'SESENTA', 'SETENTA', 'OCHENTA', 'NOVENTA'];
this.monedaSingular = " PESO";
this.monedaPlural = " PESOS";
this.monedaMillon = " DE PESOS";
this.centavoSingular = " CENTAVO"
this.centavoPlural = " CENTAVOS"
this.elMessage = document.getElementById('message');
this.addListener();
}
addListener() {
let elInput = document.getElementById('field-number');
elInput.addEventListener('keyup', () => {
if (elInput.value !== '') {
this.convertToText(elInput.value);
} else {
this.elMessage.innerText = '';
}
});
}
convertToText(number) {
number = this.deleteZerosLeft(number);
if (!this.validateNumber(number)) {
this.elMessage.innerText = 'Sólo se aceptan números enteros positivos.';
return;
}
let num = number;
number = number.split(".")[0];
let entero = this.getName(number);
let moneda;
if (parseInt(number) == 1) {
//this.elMessage.innerText =
moneda = entero + this.monedaSingular;
} else {
moneda = entero + this.monedaPlural;
}
if (num.indexOf('.') >= 0) {
let d = num.split(".")[1];
d = this.getName(d);
if (parseInt(d) == 0) {
moneda = moneda;
} else if (parseInt(d) == 1) {
moneda = moneda + " CON " + d + " " + this.centavoSingular;
} else {
moneda = moneda + " CON " + d + " " + this.centavoPlural;
}
}
this.elMessage.innerText = moneda;
}
// Elimina los ceros a la izquierda
deleteZerosLeft(number) {
let i = 0;
let isZero = true;
for (i = 0; i < number.length; i++) {
if (number.charAt(i) != 0) {
isZero = false;
break;
}
}
return isZero ? '0' : number.substr(i);
}
validateNumber(number) {
// Validar que la cadena sea un número y que no esté vacía
if (isNaN(number) || number === '') {
return false;
}
// Validar que el número no sea negativo
if (number.indexOf('-') >= 0) {
return false;
}
return true;
}
getName(number) {
number = this.deleteZerosLeft(number);
if (number.length === 1) {
return this.getUnits(number);
}
if (number.length === 2) {
return this.getTens(number);
}
if (number.length === 3) {
return this.getHundreds(number);
}
if (number.length < 7) {
return this.getThousands(number);
}
if (number.length < 13) {
return this.getPeriod(number, 6, 'MILLON');
}
if (number.length < 19) {
return this.getPeriod(number, 12, 'BILLON');
}
return 'Número demasiado grande.';
}
getUnits(number) {
let numberInt = parseInt(number);
return this.unit[numberInt];
}
getTens(number) {
// Obtener las unidades
let units = number.charAt(1);
if (number < 17) {
return this.tenToSixteen[number - 10];
}
if (number < 20) {
return 'DIECI' + this.getUnits(units);
}
// Nombres especiales
switch (number) {
case '20':
return 'VEINTE';
case '22':
return 'VEINTIDOS';
case '23':
return 'VEINTITRES';
case '26':
return 'VEINTISEIS';
}
if (number < 30) {
return 'VEINTI' + this.getUnits(units);
}
let name = this.tens[number.charAt(0) - 3];
if (units > 0) {
name += ' Y ' + this.getUnits(units);
}
return name;
}
getHundreds(number) {
let name = '';
// Obtener las centenas
let hundreds = number.charAt(0);
// Obtener las decenas y unidades
let tens = number.substr(1);
if (number == 100) {
return 'CIEN';
}
// Nombres especiales
switch(hundreds) {
case '1':
name = 'CIENTO';
break;
case '5':
name = 'QUINIENTOS';
break;
case '7':
name = 'SETECIENTOS';
break;
case '9':
name = 'NOVECIENTOS';
}
if (name === '') {
name = this.getUnits(hundreds) + 'CIENTOS';
}
if (tens > 0) {
name += ' ' + this.getName(tens);
}
return name;
}
getThousands(number) {
let name = 'MIL';
// Obtener cuantos dígitos están en los miles
let thousandsLength = number.length - 3;
// Obtener los miles
let thousands = number.substr(0, thousandsLength);
// Obtener las centenas, decenas y unidades
let hundreds = number.substr(thousandsLength);
if (thousands > 1) {
// Se reemplaza la palabra uno por un en numeros como 21000, 31000, 41000, etc.
name = this.getName(thousands).replace('UNO', 'UN') + ' MIL';
}
if (hundreds > 0) {
name += ' ' + this.getName(hundreds);
}
return name;
}
// Obtiene periodos, por ejemplo: millones, billones, etc.
getPeriod(number, digitsToTheRight, periodName) {
let name = 'UN ' + periodName;
// Obtener cuantos dígitos están dentro del periodo
let periodLength = number.length - digitsToTheRight;
// Obtener los dítos del periodo
let periodDigits = number.substr(0, periodLength);
// Obtener los digitos previos al periodo
let previousDigits = number.substr(periodLength);
if (periodDigits > 1) {
name = this.getName(periodDigits).replace('UNO', 'UN') + ' ' + periodName.replace('Ó', 'O') + 'ES';
}
if (previousDigits > 0) {
name += ' ' + this.getName(previousDigits);
}
return name;
}
}
new Converter();

Related

javascript function converting thousand digit to word [duplicate]

I'm trying to convert numbers into english words, for example 1234 would become: "one thousand two hundred thirty four".
My Tactic goes like this:
Separate the digits to three and put them on Array (finlOutPut), from right to left.
Convert each group (each cell in the finlOutPut array) of three digits to a word (this what the triConvert function does). If all the three digits are zero convert them to "dontAddBigSuffix"
From Right to left, add thousand, million, billion, etc. If the finlOutPut cell equals "dontAddBigSufix" (because it was only zeroes), don't add the word and set the cell to " " (nothing).
It seems to work pretty well, but I've got some problems with numbers like 190000009, converted to: "one hundred ninety million". Somehow it "forgets" the last numbers when there are a few zeros.
What did I do wrong? Where is the bug? Why does it not work perfectly?
function update(){
var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');
var output = '';
var numString = document.getElementById('number').value;
var finlOutPut = new Array();
if (numString == '0') {
document.getElementById('container').innerHTML = 'Zero';
return;
}
if (numString == 0) {
document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
return;
}
var i = numString.length;
i = i - 1;
//cut the number to grups of three digits and add them to the Arry
while (numString.length > 3) {
var triDig = new Array(3);
triDig[2] = numString.charAt(numString.length - 1);
triDig[1] = numString.charAt(numString.length - 2);
triDig[0] = numString.charAt(numString.length - 3);
var varToAdd = triDig[0] + triDig[1] + triDig[2];
finlOutPut.push(varToAdd);
i--;
numString = numString.substring(0, numString.length - 3);
}
finlOutPut.push(numString);
finlOutPut.reverse();
//conver each grup of three digits to english word
//if all digits are zero the triConvert
//function return the string "dontAddBigSufix"
for (j = 0; j < finlOutPut.length; j++) {
finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
}
var bigScalCntr = 0; //this int mark the million billion trillion... Arry
for (b = finlOutPut.length - 1; b >= 0; b--) {
if (finlOutPut[b] != "dontAddBigSufix") {
finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
bigScalCntr++;
}
else {
//replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
finlOutPut[b] = ' ';
bigScalCntr++; //advance the counter
}
}
//convert The output Arry to , more printable string
for(n = 0; n<finlOutPut.length; n++){
output +=finlOutPut[n];
}
document.getElementById('container').innerHTML = output;//print the output
}
//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
var hundred = ' hundred';
var output = '';
var numString = num.toString();
if (num == 0) {
return 'dontAddBigSufix';
}
//the case of 10, 11, 12 ,13, .... 19
if (num < 20) {
output = ones[num];
return output;
}
//100 and more
if (numString.length == 3) {
output = ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output += ones[parseInt(numString.charAt(2))];
return output;
}
output += tens[parseInt(numString.charAt(0))];
output += ones[parseInt(numString.charAt(1))];
return output;
}
<input type="text"
id="number"
size="70"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"/>
<br/>
<div id="container">Here The Numbers Printed</div>
JavaScript is parsing the group of 3 numbers as an octal number when there's a leading zero digit. When the group of three digits is all zeros, the result is the same whether the base is octal or decimal.
But when you give JavaScript '009' (or '008'), that's an invalid octal number, so you get zero back.
If you had gone through the whole set of numbers from 190,000,001 to 190,000,010 you'd hav seen JavaScript skip '...,008' and '...,009' but emit 'eight' for '...,010'. That's the 'Eureka!' moment.
Change:
for (j = 0; j < finlOutPut.length; j++) {
finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
}
to
for (j = 0; j < finlOutPut.length; j++) {
finlOutPut[j] = triConvert(parseInt(finlOutPut[j],10));
}
Code also kept on adding commas after every non-zero group, so I played with it and found the right spot to add the comma.
Old:
for (b = finlOutPut.length - 1; b >= 0; b--) {
if (finlOutPut[b] != "dontAddBigSufix") {
finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
bigScalCntr++;
}
else {
//replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
finlOutPut[b] = ' ';
bigScalCntr++; //advance the counter
}
}
//convert The output Arry to , more printable string
for(n = 0; n<finlOutPut.length; n++){
output +=finlOutPut[n];
}
New:
for (b = finlOutPut.length - 1; b >= 0; b--) {
if (finlOutPut[b] != "dontAddBigSufix") {
finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr]; // <<<
bigScalCntr++;
}
else {
//replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
finlOutPut[b] = ' ';
bigScalCntr++; //advance the counter
}
}
//convert The output Arry to , more printable string
var nonzero = false; // <<<
for(n = 0; n<finlOutPut.length; n++){
if (finlOutPut[n] != ' ') { // <<<
if (nonzero) output += ' , '; // <<<
nonzero = true; // <<<
} // <<<
output +=finlOutPut[n];
}
Your problem is already solved but I am posting another way of doing it just for reference.
The code was written to be tested on node.js, but the functions should work fine when called within the browser. Also, this only handles the range [0,1000000], but can be easily adapted for bigger ranges.
// actual conversion code starts here
var ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
var teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
function convert_millions(num) {
if (num >= 1000000) {
return convert_millions(Math.floor(num / 1000000)) + " million " + convert_thousands(num % 1000000);
} else {
return convert_thousands(num);
}
}
function convert_thousands(num) {
if (num >= 1000) {
return convert_hundreds(Math.floor(num / 1000)) + " thousand " + convert_hundreds(num % 1000);
} else {
return convert_hundreds(num);
}
}
function convert_hundreds(num) {
if (num > 99) {
return ones[Math.floor(num / 100)] + " hundred " + convert_tens(num % 100);
} else {
return convert_tens(num);
}
}
function convert_tens(num) {
if (num < 10) return ones[num];
else if (num >= 10 && num < 20) return teens[num - 10];
else {
return tens[Math.floor(num / 10)] + " " + ones[num % 10];
}
}
function convert(num) {
if (num == 0) return "zero";
else return convert_millions(num);
}
//end of conversion code
//testing code begins here
function main() {
var cases = [0, 1, 2, 7, 10, 11, 12, 13, 15, 19, 20, 21, 25, 29, 30, 35, 50, 55, 69, 70, 99, 100, 101, 119, 510, 900, 1000, 5001, 5019, 5555, 10000, 11000, 100000, 199001, 1000000, 1111111, 190000009];
for (var i = 0; i < cases.length; i++) {
console.log(cases[i] + ": " + convert(cases[i]));
}
}
main();
I know this problem had solved 3 years ago. I am posting this SPECIALLY FOR INDIAN DEVELOPERS
After spending some time in googling and playing with others code i made a quick fix and reusable function works well for numbers upto 99,99,99,999. use : number2text(1234.56); will return ONE THOUSAND TWO HUNDRED AND THIRTY-FOUR RUPEE AND FIFTY-SIX PAISE ONLY . enjoy !
function number2text(value) {
var fraction = Math.round(frac(value)*100);
var f_text = "";
if(fraction > 0) {
f_text = "AND "+convert_number(fraction)+" PAISE";
}
return convert_number(value)+" RUPEE "+f_text+" ONLY";
}
function frac(f) {
return f % 1;
}
function convert_number(number)
{
if ((number < 0) || (number > 999999999))
{
return "NUMBER OUT OF RANGE!";
}
var Gn = Math.floor(number / 10000000); /* Crore */
number -= Gn * 10000000;
var kn = Math.floor(number / 100000); /* lakhs */
number -= kn * 100000;
var Hn = Math.floor(number / 1000); /* thousand */
number -= Hn * 1000;
var Dn = Math.floor(number / 100); /* Tens (deca) */
number = number % 100; /* Ones */
var tn= Math.floor(number / 10);
var one=Math.floor(number % 10);
var res = "";
if (Gn>0)
{
res += (convert_number(Gn) + " CRORE");
}
if (kn>0)
{
res += (((res=="") ? "" : " ") +
convert_number(kn) + " LAKH");
}
if (Hn>0)
{
res += (((res=="") ? "" : " ") +
convert_number(Hn) + " THOUSAND");
}
if (Dn)
{
res += (((res=="") ? "" : " ") +
convert_number(Dn) + " HUNDRED");
}
var ones = Array("", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX","SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN","FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN","NINETEEN");
var tens = Array("", "", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY","SEVENTY", "EIGHTY", "NINETY");
if (tn>0 || one>0)
{
if (!(res==""))
{
res += " AND ";
}
if (tn < 2)
{
res += ones[tn * 10 + one];
}
else
{
res += tens[tn];
if (one>0)
{
res += ("-" + ones[one]);
}
}
}
if (res=="")
{
res = "zero";
}
return res;
}
Indian Version
Updated version of #jasonhao 's answer for Indian currency
function intToEnglish(number) {
var NS = [
{ value: 10000000, str: "Crore" },
{ value: 100000, str: "Lakh" },
{ value: 1000, str: "Thousand" },
{ value: 100, str: "Hundred" },
{ value: 90, str: "Ninety" },
{ value: 80, str: "Eighty" },
{ value: 70, str: "Seventy" },
{ value: 60, str: "Sixty" },
{ value: 50, str: "Fifty" },
{ value: 40, str: "Forty" },
{ value: 30, str: "Thirty" },
{ value: 20, str: "Twenty" },
{ value: 19, str: "Nineteen" },
{ value: 18, str: "Eighteen" },
{ value: 17, str: "Seventeen" },
{ value: 16, str: "Sixteen" },
{ value: 15, str: "Fifteen" },
{ value: 14, str: "Fourteen" },
{ value: 13, str: "Thirteen" },
{ value: 12, str: "Twelve" },
{ value: 11, str: "Eleven" },
{ value: 10, str: "Ten" },
{ value: 9, str: "Nine" },
{ value: 8, str: "Eight" },
{ value: 7, str: "Seven" },
{ value: 6, str: "Six" },
{ value: 5, str: "Five" },
{ value: 4, str: "Four" },
{ value: 3, str: "Three" },
{ value: 2, str: "Two" },
{ value: 1, str: "One" }
];
var result = '';
for (var n of NS) {
if (number >= n.value) {
if (number <= 99) {
result += n.str;
number -= n.value;
if (number > 0) result += ' ';
} else {
var t = Math.floor(number / n.value);
// console.log(t);
var d = number % n.value;
if (d > 0) {
return intToEnglish(t) + ' ' + n.str + ' ' + intToEnglish(d);
} else {
return intToEnglish(t) + ' ' + n.str;
}
}
}
}
return result;
}
console.log(intToEnglish(99))
console.log(intToEnglish(991199))
console.log(intToEnglish(123456799))
There are JS library for en_US and cs_CZ.
You can use it standalone or as Node module.
Numbers2Words
Here, I wrote an alternative solution:
1) The object containing the string constants:
var NUMBER2TEXT = {
ones: ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
tens: ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'],
sep: ['', ' thousand ', ' million ', ' billion ', ' trillion ', ' quadrillion ', ' quintillion ', ' sextillion ']
};
2) The actual code:
(function( ones, tens, sep ) {
var input = document.getElementById( 'input' ),
output = document.getElementById( 'output' );
input.onkeyup = function() {
var val = this.value,
arr = [],
str = '',
i = 0;
if ( val.length === 0 ) {
output.textContent = 'Please type a number into the text-box.';
return;
}
val = parseInt( val, 10 );
if ( isNaN( val ) ) {
output.textContent = 'Invalid input.';
return;
}
while ( val ) {
arr.push( val % 1000 );
val = parseInt( val / 1000, 10 );
}
while ( arr.length ) {
str = (function( a ) {
var x = Math.floor( a / 100 ),
y = Math.floor( a / 10 ) % 10,
z = a % 10;
return ( x > 0 ? ones[x] + ' hundred ' : '' ) +
( y >= 2 ? tens[y] + ' ' + ones[z] : ones[10*y + z] );
})( arr.shift() ) + sep[i++] + str;
}
output.textContent = str;
};
})( NUMBER2TEXT.ones, NUMBER2TEXT.tens, NUMBER2TEXT.sep );
Live demo: http://jsfiddle.net/j5kdG/
A version with a compact object - for numbers from zero to 999.
function wordify(n) {
var word = [],
numbers = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', t3: 'Thir', t5: 'Fif', t8: 'Eigh', 20: 'Twenty' },
hundreds = 0 | (n % 1000) / 100,
tens = 0 | (n % 100) / 10,
ones = n % 10,
part;
if (n === 0) return 'Zero';
if (hundreds) word.push(numbers[hundreds] + ' Hundred');
if (tens === 0) {
word.push(numbers[ones]);
} else if (tens === 1) {
word.push(numbers['1' + ones] || (numbers['t' + ones] || numbers[ones]) + 'teen');
} else {
part = numbers[tens + '0'] || (numbers['t' + tens] || numbers[tens]) + 'ty';
word.push(numbers[ones] ? part + '-' + numbers[ones] : part);
}
return word.join(' ');
}
var i,
output = document.getElementById('out');
for (i = 0; i < 1e3; i++) output.innerHTML += wordify(i) + '\n';
<pre id="out"></pre>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
var th = ['', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion'];
var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function update(){
var numString = document.getElementById('number').value;
if (numString == '0') {
document.getElementById('container').innerHTML = 'Zero';
return;
}
if (numString == 0) {
document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
return;
}
var output = toWords(numString);
//print the output
document.getElementById('container').innerHTML = output;
}
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
} else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
} else if (n[i] != 0) {
str += dg[n[i]] + ' ';
if ((x - i) % 3 == 0) str += 'hundred ';
sk = 1;
}
if ((x - i) % 3 == 1) {
if (sk) str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
return str.replace(/\s+/g, ' ');
}
</script>
</head>
<body>
<input type="text"
id="number"
size="70"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"/>
<br/>
<div id="container">Here The Numbers Printed</div>
</body>
</html>
Try this,convert number to words
function convert(number) {
if (number < 0) {
console.log("Number Must be greater than zero = " + number);
return "";
}
if (number > 100000000000000000000) {
console.log("Number is out of range = " + number);
return "";
}
if (!is_numeric(number)) {
console.log("Not a number = " + number);
return "";
}
var quintillion = Math.floor(number / 1000000000000000000); /* quintillion */
number -= quintillion * 1000000000000000000;
var quar = Math.floor(number / 1000000000000000); /* quadrillion */
number -= quar * 1000000000000000;
var trin = Math.floor(number / 1000000000000); /* trillion */
number -= trin * 1000000000000;
var Gn = Math.floor(number / 1000000000); /* billion */
number -= Gn * 1000000000;
var million = Math.floor(number / 1000000); /* million */
number -= million * 1000000;
var Hn = Math.floor(number / 1000); /* thousand */
number -= Hn * 1000;
var Dn = Math.floor(number / 100); /* Tens (deca) */
number = number % 100; /* Ones */
var tn = Math.floor(number / 10);
var one = Math.floor(number % 10);
var res = "";
if (quintillion > 0) {
res += (convert_number(quintillion) + " quintillion");
}
if (quar > 0) {
res += (convert_number(quar) + " quadrillion");
}
if (trin > 0) {
res += (convert_number(trin) + " trillion");
}
if (Gn > 0) {
res += (convert_number(Gn) + " billion");
}
if (million > 0) {
res += (((res == "") ? "" : " ") + convert_number(million) + " million");
}
if (Hn > 0) {
res += (((res == "") ? "" : " ") + convert_number(Hn) + " Thousand");
}
if (Dn) {
res += (((res == "") ? "" : " ") + convert_number(Dn) + " hundred");
}
var ones = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", "Nineteen");
var tens = Array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eigthy", "Ninety");
if (tn > 0 || one > 0) {
if (!(res == "")) {
res += " and ";
}
if (tn < 2) {
res += ones[tn * 10 + one];
} else {
res += tens[tn];
if (one > 0) {
res += ("-" + ones[one]);
}
}
}
if (res == "") {
console.log("Empty = " + number);
res = "";
}
return res;
}
function is_numeric(mixed_var) {
return (typeof mixed_var === 'number' || typeof mixed_var === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}
function intToEnglish(number){
var NS = [
{value: 1000000000000000000000, str: "sextillion"},
{value: 1000000000000000000, str: "quintillion"},
{value: 1000000000000000, str: "quadrillion"},
{value: 1000000000000, str: "trillion"},
{value: 1000000000, str: "billion"},
{value: 1000000, str: "million"},
{value: 1000, str: "thousand"},
{value: 100, str: "hundred"},
{value: 90, str: "ninety"},
{value: 80, str: "eighty"},
{value: 70, str: "seventy"},
{value: 60, str: "sixty"},
{value: 50, str: "fifty"},
{value: 40, str: "forty"},
{value: 30, str: "thirty"},
{value: 20, str: "twenty"},
{value: 19, str: "nineteen"},
{value: 18, str: "eighteen"},
{value: 17, str: "seventeen"},
{value: 16, str: "sixteen"},
{value: 15, str: "fifteen"},
{value: 14, str: "fourteen"},
{value: 13, str: "thirteen"},
{value: 12, str: "twelve"},
{value: 11, str: "eleven"},
{value: 10, str: "ten"},
{value: 9, str: "nine"},
{value: 8, str: "eight"},
{value: 7, str: "seven"},
{value: 6, str: "six"},
{value: 5, str: "five"},
{value: 4, str: "four"},
{value: 3, str: "three"},
{value: 2, str: "two"},
{value: 1, str: "one"}
];
var result = '';
for (var n of NS) {
if(number>=n.value){
if(number<=20){
result += n.str;
number -= n.value;
if(number>0) result += ' ';
}else{
var t = Math.floor(number / n.value);
var d = number % n.value;
if(d>0){
return intToEnglish(t) + ' ' + n.str +' ' + intToEnglish(d);
}else{
return intToEnglish(t) + ' ' + n.str;
}
}
}
}
return result;
}
This is a simple ES6+ number to words function. You can simply add 'illions' array to extend digits. American English version.
(no 'and' before the end)
// generic number to words
let digits = ['','one','two','three','four', 'five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
let ties = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
let illions = ['', 'thousand', 'million', 'billion', 'trillion'].reverse()
let join = (a, s) => a.filter(v => v).join(s || ' ')
let tens = s =>
digits[s] ||
join([ties[s[0]], digits[s[1]]], '-') // 21 -> twenty-one
let hundreds = s =>
join(
(s[0] !== '0' ? [digits[s[0]], 'hundred'] : [])
.concat( tens(s.substr(1,2)) ) )
let re = '^' + '(\\d{3})'.repeat(illions.length) + '$'
let numberToWords = n =>
// to filter non number or '', null, undefined, false, NaN
isNaN(Number(n)) || !n && n !== 0
? 'not a number'
: Number(n) === 0
? 'zero'
: Number(n) >= 10 ** (illions.length * 3)
? 'too big'
: String(n)
.padStart(illions.length * 3, '0')
.match(new RegExp(re))
.slice(1, illions.length + 1)
.reduce( (a, v, i) => v === '000' ? a : join([a, hundreds(v), illions[i]]), '')
// just for this question.
let update = () => {
let value = document.getElementById('number').value
document.getElementById('container').innerHTML = numberToWords(value)
}
Here's a solution that will handle any integer value that fit's in a string. I've defined number scales up to "decillion", so this solution should be accurate up to 999 decillion. After which you get things like "one thousand decillion" and so on.
JavaScript numbers start to fail around "999999999999999" so the convert function works with strings of numbers only.
Examples:
convert("365");
//=> "three hundred sixty-five"
convert("10000000000000000000000000000230001010109");
//=> "ten thousand decillion two hundred thirty billion one million ten thousand one hundred nine"
Code:
var lt20 = ["", "one", "two", "three", "four", "five", "six", "seven","eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ],
tens = ["", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eightty", "ninety" ],
scales = ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion" ],
max = scales.length * 3;
function convert(val) {
var len;
// special cases
if (val[0] === "-") { return "negative " + convert(val.slice(1)); }
if (val === "0") { return "zero"; }
val = trim_zeros(val);
len = val.length;
// general cases
if (len < max) { return convert_lt_max(val); }
if (len >= max) { return convert_max(val); }
}
function convert_max(val) {
return split_rl(val, max)
.map(function (val, i, arr) {
if (i < arr.length - 1) {
return convert_lt_max(val) + " " + scales.slice(-1);
}
return convert_lt_max(val);
})
.join(" ");
}
function convert_lt_max(val) {
var l = val.length;
if (l < 4) {
return convert_lt1000(val).trim();
} else {
return split_rl(val, 3)
.map(convert_lt1000)
.reverse()
.map(with_scale)
.reverse()
.join(" ")
.trim();
}
}
function convert_lt1000(val) {
var rem, l;
val = trim_zeros(val);
l = val.length;
if (l === 0) { return ""; }
if (l < 3) { return convert_lt100(val); }
if (l === 3) { //less than 1000
rem = val.slice(1);
if (rem) {
return lt20[val[0]] + " hundred " + convert_lt1000(rem);
} else {
return lt20[val[0]] + " hundred";
}
}
}
function convert_lt100(val) {
if (is_lt20(val)) { // less than 20
return lt20[val];
} else if (val[1] === "0") {
return tens[val[0]];
} else {
return tens[val[0]] + "-" + lt20[val[1]];
}
}
function split_rl(str, n) {
// takes a string 'str' and an integer 'n'. Splits 'str' into
// groups of 'n' chars and returns the result as an array. Works
// from right to left.
if (str) {
return Array.prototype.concat
.apply(split_rl(str.slice(0, (-n)), n), [str.slice(-n)]);
} else {
return [];
}
}
function with_scale(str, i) {
var scale;
if (str && i > (-1)) {
scale = scales[i];
if (scale !== undefined) {
return str.trim() + " " + scale;
} else {
return convert(str.trim());
}
} else {
return "";
}
}
function trim_zeros(val) {
return val.replace(/^0*/, "");
}
function is_lt20(val) {
return parseInt(val, 10) < 20;
}
I've modified the posting from Šime Vidas - http://jsfiddle.net/j5kdG/
To include dollars, cents, commas and "and" in the appropriate places.
There's an optional ending if it requires "zero cents" or no mention of cents if 0.
This function structure did my head in a bit but I learned heaps. Thanks Sime.
Someone might find a better way of processing this.
Code:
var str='';
var str2='';
var str3 =[];
function convertNum(inp,end){
str2='';
str3 = [];
var NUMBER2TEXT = {
ones: ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
tens: ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'],
sep: ['', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion', ' sextillion']
};
(function( ones, tens, sep ) {
var vals = inp.split("."),val,pos,postsep=' ';
for (p in vals){
val = vals[p], arr = [], str = '', i = 0;
if ( val.length === 0 ) {return 'No value';}
val = parseInt( (p==1 && val.length===1 )?val*10:val, 10 );
if ( isNaN( val ) || p>=2) {return 'Invalid value'; }
while ( val ) {
arr.push( val % 1000 );
val = parseInt( val / 1000, 10 );
}
pos = arr.length;
function trimx (strx) {
return strx.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function seps(sepi,i){
var s = str3.length
if (str3[s-1][0]){
if (str3[s-2][1] === str3[s-1][0]){
str = str.replace(str3[s-2][1],'')
}
}
var temp = str.split(sep[i-2]);
if (temp.length > 1){
if (trimx(temp[0]) ==='' && temp[1].length > 1 ){
str = temp[1];
}
}
return sepi + str ;
}
while ( arr.length ) {
str = (function( a ) {
var x = Math.floor( a / 100 ),
y = Math.floor( a / 10 ) % 10,
z = a % 10;
postsep = (arr.length != 0)?', ' : ' ' ;
if ((x+y+z) === 0){
postsep = ' '
}else{
if (arr.length == pos-1 && x===0 && pos > 1 ){
postsep = ' and '
}
}
str3.push([trimx(str)+"",trimx(sep[i])+""]);
return (postsep)+( x > 0 ? ones[x] + ' hundred ' + (( x == 0 && y >= 0 || z >0 )?' and ':' ') : ' ' ) +
( y >= 2 ? tens[y] + ((z===0)?' ':'-') + ones[z] : ones[10*y + z] );
})( arr.shift() ) +seps( sep[i++] ,i ) ;
}
if (p==0){ str2 += str + ' dollars'}
if (p==1 && !end){str2 += (str!='')?' and '+ str + ' cents':'' }
if (p==1 && end ){str2 += ' and ' + ((str==='')?'zero':str) + ' cents '}
}
})( NUMBER2TEXT.ones , NUMBER2TEXT.tens , NUMBER2TEXT.sep );
this is the solution for french language
it's a fork for #gandil response
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
var th = ['', ' mille', ' millions', ' milliards', ' billions', ' mille-billions', ' trillion'];
var dg = ['zéro', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf'];
var tn = ['dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf'];
var tw = ['vingt', 'trente', 'quarante', 'cinquante', 'soixante', 'soixante-dix', 'quatre-vingts', 'quatre-vingt-dix'];
function update(){
var numString = document.getElementById('number').value;
if (numString == '0') {
document.getElementById('container').innerHTML = 'Zéro';
return;
}
if (numString == 0) {
document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
return;
}
var output = toWords(numString);
//output.split('un mille').join('msille ');
//output.replace('un cent', 'cent ');
//print the output
//if(output.length == 4){output = 'sss';}
document.getElementById('container').innerHTML = output;
}
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
} else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
} else if (n[i] != 0) {
str += dg[n[i]] + ' ';
//if((dg[n[i]] == 'un') && ((x - i) / 3 == 1)){str = 'cent ';}
if ((x - i) % 3 == 0) {str += 'cent ';}
sk = 1;
}
if ((x - i) % 3 == 1) {
//test
if((x - i - 1) / 3 == 1){
var long = str.length;
subs = str.substr(long-3);
if(subs.search("un")!= -1){
//str += 'OK';
str = str.substr(0, long-4);
}
}
//test
if (sk) str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
//if(str.length == 4){}
str.replace(/\s+/g, ' ');
return str.split('un cent').join('cent ');
//return str.replace('un cent', 'cent ');
}
</script>
</head>
<body>
<input type="text"
id="number"
size="70"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"/>
<br/>
<div id="container">Here The Numbers Printed</div>
</body>
</html>
i hope it will help
A little code snippet for INDONESIAN DEVELOPER to translate numeric value into verbal spelling (minimized by hand, only 576 bytes, requires ES6+)...
const terbilang=(x,nol='---',min='minus')=>{const S=['','satu','dua','tiga','empat','lima','enam','tujuh','delapan','sembilan'],K=['','ribu','juta','miliar','triliun','kuadriliun'],s=[];if(!x)return nol;if(x<0){if(min)s=[min];x=-x}for(let k=0;x;k++){let g=x%1e3;if(g===1&&k===1)s.unshift('seribu');else{let u=g>99?[(g>199?S[g/100|0]+' ':'se')+'ratus']:[];if(g%=100){if(g>9&&g<20)u.push(g<11?'sepuluh':(g<12?'se':S[g%10]+' ')+'belas');else{if(g>19)u.push(S[g/10|0]+' puluh');if(g%=10)u.push(S[g])}}k&&u.push(K[k]);s.unshift(u.join(' '))}x=Math.floor(x/1e3)}return s.join(' ')};
function toWords(...x) {
let space = /\s/g;
let digit = /\d/g;
let trio = /.../g;
let unit = ' one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'.split(space);
let ten = ' twenty thirty forty fifty sixty seventy eighty ninety'.split(space);
let scale = ' thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion'.split(space);
let d = digit.test(x) ? String(x).match(digit) : ['0'];
while (d.length % 3) d.unshift('0');
d = d.join('').match(trio).map(function verbose(string) {
let number = Number(string);
return (number < 20) ?
unit[number] :
(number < 100) ?
[ten[Number(string.slice(0, -1))], verbose(string.slice(-1))].filter(Boolean).join('-') :
[verbose(string.slice(0, -2)), 'hundred', verbose(string.slice(-2))].filter(Boolean).join(' ');
}).reverse().map(function(v, i, a) {
return v ? [v, scale[i]].filter(Boolean).join(' ') : v;
}).reverse().filter(Boolean).join(', ');
return d ? d : 'zero';
}
toWords('14,702,000,583,690,010');
// 'fourteen quadrillion, seven hundred two trillion, five hundred eighty-three million, six hundred ninety thousand, ten'
Update Feb 2022
A simple and short Javascript function to do the conversion of numbers (integers) to words in English (US System) and give the correct results is included below using a forEach() loop with the String Triplets Array method.
The number is first converted into a string triplet array using:
num= ("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
The string array is then easily decoded into numbers.
For example, the number 1234567 is converted into an array of string triplets:
[ '001', '234', '567' ]
Each element is then scanned from left to right by the forEach() loop.
This is a far better solution than using a for loop that I had proposed 2 years ago.
You can increase the scale array above the 'Quadrillion' if you prefer.
If the input number is too large, then pass it as a "string".
Test cases are also included.
/********************************************************
* #function : numToWords(number)
* #purpose : Converts Unsigned Integers to Words
* #version : 1.50
* #author : Mohsen Alyafei
* #licence : MIT
* #date : 26 Feb 2022
* #param : {number} [integer numeric or string]
* #returns : {string} The wordified number string
********************************************************/
//==============================================================
function numToWords(num = 0) {
if (num == 0) return "Zero";
num= ("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
let out="",
T10s=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
T20s=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],
sclT=["","Thousand","Million","Billion","Trillion","Quadrillion"];
return num.forEach((n,i) => {
if (+n) {
let hund=+n[0], ten=+n.substring(1), scl=sclT[num.length-i-1];
out+=(out?" ":"")+(hund?T10s[hund]+" Hundred":"")+(hund && ten?" ":"")+(ten<20?T10s[ten]:T20s[+n[1]]+(+n[2]?"-":"")+T10s[+n[2]]);
out+=(out && scl?" ":"")+scl;
}}),out;
}
//==============================================================
//=========================================
// Test Code
//=========================================
var r=0; // test tracker
r |= test(0,"Zero");
r |= test(5,"Five");
r |= test(10,"Ten");
r |= test(19,"Nineteen");
r |= test(33,"Thirty-Three");
r |= test(100,"One Hundred");
r |= test(111,"One Hundred Eleven");
r |= test(890,"Eight Hundred Ninety");
r |= test(1234,"One Thousand Two Hundred Thirty-Four");
r |= test(12345,"Twelve Thousand Three Hundred Forty-Five");
r |= test(123456,"One Hundred Twenty-Three Thousand Four Hundred Fifty-Six");
r |= test(1234567,"One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven");
r |= test(12345678,"Twelve Million Three Hundred Forty-Five Thousand Six Hundred Seventy-Eight");
r |= test(123456789,"One Hundred Twenty-Three Million Four Hundred Fifty-Six Thousand Seven Hundred Eighty-Nine");
r |= test(1234567890,"One Billion Two Hundred Thirty-Four Million Five Hundred Sixty-Seven Thousand Eight Hundred Ninety");
r |= test(1001,"One Thousand One");
r |= test(10001,"Ten Thousand One");
r |= test(100001,"One Hundred Thousand One");
r |= test(1000001,"One Million One");
r |= test(10000001,"Ten Million One");
r |= test(100000001,"One Hundred Million One");
r |= test(12012,"Twelve Thousand Twelve");
r |= test(120012,"One Hundred Twenty Thousand Twelve");
r |= test(1200012,"One Million Two Hundred Thousand Twelve");
r |= test(12000012,"Twelve Million Twelve");
r |= test(120000012,"One Hundred Twenty Million Twelve");
r |= test(75075,"Seventy-Five Thousand Seventy-Five");
r |= test(750075,"Seven Hundred Fifty Thousand Seventy-Five");
r |= test(7500075,"Seven Million Five Hundred Thousand Seventy-Five");
r |= test(75000075,"Seventy-Five Million Seventy-Five");
r |= test(750000075,"Seven Hundred Fifty Million Seventy-Five");
r |= test(1000,"One Thousand");
r |= test(1000000,"One Million");
r |= test(1000000000,"One Billion");
r |= test(1000000000000,"One Trillion");
r |= test("1000000000000000","One Quadrillion");
if (r==0) console.log("All Test Cases Passed.");
function test(n,should) {
let result = numToWords(n);
if (result !== should) {console.log(`${n} Output : ${result}\n${n} Should be: ${should}`);return 1;}
}
I would like to point out that the original logic fails for values between x11-x19, where x >= 1. For example, 118 returns "one hundred eight". This is because these numbers are processed by the following code in triConvert():
//100 and more
if (numString.length == 3) {
output = ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output += ones[parseInt(numString.charAt(2))];
return output;
}
here, the character representing the tens digit is used to index the tens[] array, which has an empty string at index [1], so 118 become 108 in effect.
It might be better to deal with the hundreds (if any first), then run the ones and tens through the same logic. Instead of:
//the case of 10, 11, 12 ,13, .... 19
if (num < 20) {
output = ones[num];
return output;
}
//100 and more
if (numString.length == 3) {
output = ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output += ones[parseInt(numString.charAt(2))];
return output;
}
output += tens[parseInt(numString.charAt(0))];
output += ones[parseInt(numString.charAt(1))];
return output;
I would suggest:
// 100 and more
if ( numString.length == 3 )
{
output = hundreds[ parseInt( numString.charAt(0) ) ] + hundred ;
num = num % 100 ;
numString = num.toString() ;
}
if ( num < 20 )
{
output += ones[num] ;
}
else
{ // 20-99
output += tens[ parseInt( numString.charAt(0) ) ] ;
output += '-' + ones[ parseInt( numString.charAt(1) ) ] ;
}
return output;
It seems to me that the suggested code is both shorter and clearer, but I might be biased ;-)
Source: http://javascript.about.com/library/bltoword.htm
Smallest script that I found:
<script type="text/javascript" src="toword.js">
var words = toWords(12345);
console.log(words);
</script>
Enjoy!
I tried Muhammad's solution, but had some issues and wanted to use decimals so I made some changes and converted to coffeescript and angular. Please bear in mind that js and coffeescript are not my strong suits, so use with care.
$scope.convert = (number, upper=0) ->
number = +number
# console.log "inside convert and the number is: " + number
if number < 0
# console.log 'Number Must be greater than zero = ' + number
return ''
if number > 100000000000000000000
# console.log 'Number is out of range = ' + number
return ''
if isNaN(number)
console.log("NOT A NUMBER")
alert("Not a number = ")
return ''
else
console.log "at line 88 number is: " + number
quintillion = Math.floor(number / 1000000000000000000)
### quintillion ###
number -= quintillion * 1000000000000000000
quar = Math.floor(number / 1000000000000000)
# console.log "at line 94 number is: " + number
### quadrillion ###
number -= quar * 1000000000000000
trin = Math.floor(number / 1000000000000)
# console.log "at line 100 number is: " + number
### trillion ###
number -= trin * 1000000000000
Gn = Math.floor(number / 1000000000)
# console.log "at line 105 number is: " + number
### billion ###
number -= Gn * 1000000000
million = Math.floor(number / 1000000)
# console.log "at line 111 number is: " + number
### million ###
number -= million * 1000000
Hn = Math.floor(number / 1000)
# console.log "at line 117 number is: " + number
### thousand ###
number -= Hn * 1000
Dn = Math.floor(number / 100)
# console.log "at line 123 number is: " + number
### Tens (deca) ###
number = number % 100
# console.log "at line 128 number is: " + number
### Ones ###
tn = Math.floor(number / 10)
one = Math.floor(number % 10)
# tn = Math.floor(number / 1)
change = Math.round((number % 1) * 100)
res = ''
# console.log "before ifs"
if quintillion > 0
res += $scope.convert(quintillion) + ' Quintillion'
if quar > 0
res += $scope.convert(quar) + ' Quadrillion'
if trin > 0
res += $scope.convert(trin) + ' Trillion'
if Gn > 0
res += $scope.convert(Gn) + ' Billion'
if million > 0
res += (if res == '' then '' else ' ') + $scope.convert(million) + ' Million'
if Hn > 0
res += (if res == '' then '' else ' ') + $scope.convert(Hn) + ' Thousand'
if Dn
res += (if res == '' then '' else ' ') + $scope.convert(Dn) + ' Hundred'
# console.log "the result is: " + res
ones = Array('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eightteen', 'Nineteen')
tens = Array('', '', 'Twenty', 'Thirty', 'Fourty', 'Fifty', 'Sixty', 'Seventy', 'Eigthy', 'Ninety')
# console.log "the result at 161 is: " + res
if tn > 0 or one > 0
if !(res == '')
# res += ' and '
res += ' '
# console.log "the result at 164 is: " + res
if tn < 2
res += ones[tn * 10 + one]
# console.log "the result at 168is: " + res
else
res += tens[tn]
if one > 0
res += '-' + ones[one]
# console.log "the result at 173 is: " + res
if change > 0
if res == ''
res = change + "/100"
else
res += ' and ' + change + "/100"
if res == ''
console.log 'Empty = ' + number
res = ''
if +upper == 1
res = res.toUpperCase()
$scope.newCheck.amountInWords = res
return res
$scope.is_numeric = (mixed_var) ->
# console.log "mixed var is: " + mixed_var
(typeof mixed_var == 'number' or typeof mixed_var == 'string') and mixed_var != '' and !isNaN(mixed_var)
Here is another version from me with some unit tests.
Don't use it with numbers larger than Number.MAX_SAFE_INTEGER.
describe("English Numerals Converter", function () {
assertNumeral(0, "zero");
assertNumeral(1, "one");
assertNumeral(2, "two");
assertNumeral(3, "three");
assertNumeral(4, "four");
assertNumeral(5, "five");
assertNumeral(6, "six");
assertNumeral(7, "seven");
assertNumeral(8, "eight");
assertNumeral(9, "nine");
assertNumeral(10, "ten");
assertNumeral(11, "eleven");
assertNumeral(12, "twelve");
assertNumeral(13, "thirteen");
assertNumeral(14, "fourteen");
assertNumeral(15, "fifteen");
assertNumeral(16, "sixteen");
assertNumeral(17, "seventeen");
assertNumeral(18, "eighteen");
assertNumeral(19, "nineteen");
assertNumeral(20, "twenty");
assertNumeral(21, "twenty-one");
assertNumeral(22, "twenty-two");
assertNumeral(23, "twenty-three");
assertNumeral(30, "thirty");
assertNumeral(37, "thirty-seven");
assertNumeral(40, "forty");
assertNumeral(50, "fifty");
assertNumeral(60, "sixty");
assertNumeral(70, "seventy");
assertNumeral(80, "eighty");
assertNumeral(90, "ninety");
assertNumeral(99, "ninety-nine");
assertNumeral(100, "one hundred");
assertNumeral(101, "one hundred and one");
assertNumeral(102, "one hundred and two");
assertNumeral(110, "one hundred and ten");
assertNumeral(120, "one hundred and twenty");
assertNumeral(121, "one hundred and twenty-one");
assertNumeral(199, "one hundred and ninety-nine");
assertNumeral(200, "two hundred");
assertNumeral(999, "nine hundred and ninety-nine");
assertNumeral(1000, "one thousand");
assertNumeral(1001, "one thousand and one");
assertNumeral(1011, "one thousand and eleven");
assertNumeral(1111, "one thousand and one hundred and eleven");
assertNumeral(9999, "nine thousand and nine hundred and ninety-nine");
assertNumeral(10000, "ten thousand");
assertNumeral(20000, "twenty thousand");
assertNumeral(21000, "twenty-one thousand");
assertNumeral(90000, "ninety thousand");
assertNumeral(90001, "ninety thousand and one");
assertNumeral(90100, "ninety thousand and one hundred");
assertNumeral(90901, "ninety thousand and nine hundred and one");
assertNumeral(90991, "ninety thousand and nine hundred and ninety-one");
assertNumeral(90999, "ninety thousand and nine hundred and ninety-nine");
assertNumeral(91000, "ninety-one thousand");
assertNumeral(99999, "ninety-nine thousand and nine hundred and ninety-nine");
assertNumeral(100000, "one hundred thousand");
assertNumeral(999000, "nine hundred and ninety-nine thousand");
assertNumeral(1000000, "one million");
assertNumeral(10000000, "ten million");
assertNumeral(100000000, "one hundred million");
assertNumeral(1000000000, "one billion");
assertNumeral(1000000000000, "one trillion");
assertNumeral(1000000000000000, "one quadrillion");
assertNumeral(1000000000000000000, "one quintillion");
assertNumeral(1000000000000000000000, "one sextillion");
assertNumeral(-1, "minus one");
assertNumeral(-999, "minus nine hundred and ninety-nine");
function assertNumeral(number, numeral) {
it(number + " is " + numeral, function () {
expect(convert(number)).toBe(numeral);
});
}
});
function convert(n) {
let NUMERALS = [
{value: 1000000000000000000000, str: "sextillion"},
{value: 1000000000000000000, str: "quintillion"},
{value: 1000000000000000, str: "quadrillion"},
{value: 1000000000000, str: "trillion"},
{value: 1000000000, str: "billion"},
{value: 1000000, str: "million"},
{value: 1000, str: "thousand"},
{value: 100, str: "hundred"},
{value: 90, str: "ninety"},
{value: 80, str: "eighty"},
{value: 70, str: "seventy"},
{value: 60, str: "sixty"},
{value: 50, str: "fifty"},
{value: 40, str: "forty"},
{value: 30, str: "thirty"},
{value: 20, str: "twenty"},
{value: 19, str: "nineteen"},
{value: 18, str: "eighteen"},
{value: 17, str: "seventeen"},
{value: 16, str: "sixteen"},
{value: 15, str: "fifteen"},
{value: 14, str: "fourteen"},
{value: 13, str: "thirteen"},
{value: 12, str: "twelve"},
{value: 11, str: "eleven"},
{value: 10, str: "ten"},
{value: 9, str: "nine"},
{value: 8, str: "eight"},
{value: 7, str: "seven"},
{value: 6, str: "six"},
{value: 5, str: "five"},
{value: 4, str: "four"},
{value: 3, str: "three"},
{value: 2, str: "two"},
{value: 1, str: "one"}
];
if (n < 0) {
return "minus " + convert(-n);
} else if (n === 0) {
return "zero";
} else {
let result = "";
for (let numeral of NUMERALS) {
if (n >= numeral.value) {
if (n < 100) {
result += numeral.str;
n -= numeral.value;
if (n > 0) result += "-";
} else {
let times = Math.floor(n / numeral.value);
result += convert(times) + " " + numeral.str;
n -= numeral.value * times;
if (n > 0) result += " and ";
}
}
}
return result;
}
}
<script src="http://www.ittutorials.in/js/demo/numtoword.js" type="text/javascript"></script>
HTML - Convert numbers to words using JavaScript</h1>
<input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);" onkeyup="NumToWord(this.value,'divDisplayWords');"
maxlength="9" style="background-color: #efefef; border: 2px solid #CCCCC; font-size: large" />
<br />
<br />
<div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;">
</div>
I think, I have solution that's simpler and easier to understand; it goes by slicing the number, it works up to 99 lakhs crore.
function convert_to_word(num, ignore_ten_plus_check) {
var ones = [];
var tens = [];
var ten_plus = [];
ones["1"] = "one";
ones["2"] = "two";
ones["3"] = "three";
ones["4"] = "four";
ones["5"] = "five";
ones["6"] = "six";
ones["7"] = "seven";
ones["8"] = "eight";
ones["9"] = "nine";
ten_plus["10"] = "ten";
ten_plus["11"] = "eleven";
ten_plus["12"] = "twelve";
ten_plus["13"] = "thirteen";
ten_plus["14"] = "fourteen";
ten_plus["15"] = "fifteen";
ten_plus["16"] = "sixteen";
ten_plus["17"] = "seventeen";
ten_plus["18"] = "eighteen";
ten_plus["19"] = "nineteen";
tens["1"] = "ten";
tens["2"] = "twenty";
tens["3"] = "thirty";
tens["4"] = "fourty";
tens["5"] = "fifty";
tens["6"] = "sixty";
tens["7"] = "seventy";
tens["8"] = "eighty";
tens["9"] = "ninety";
var len = num.length;
if(ignore_ten_plus_check != true && len >= 2) {
var ten_pos = num.slice(len - 2, len - 1);
if(ten_pos == "1") {
return ten_plus[num.slice(len - 2, len)];
} else if(ten_pos != 0) {
return tens[num.slice(len - 2, len - 1)] + " " + ones[num.slice(len - 1, len)];
}
}
return ones[num.slice(len - 1, len)];
}
function get_rupees_in_words(str, recursive_call_count) {
if(recursive_call_count > 1) {
return "conversion is not feasible";
}
var len = str.length;
var words = convert_to_word(str, false);
if(len == 2 || len == 1) {
if(recursive_call_count == 0) {
words = words +" rupees";
}
return words;
}
if(recursive_call_count == 0) {
words = " and " + words +" rupees";
}
var hundred = convert_to_word(str.slice(0, len-2), true);
words = hundred != undefined ? hundred + " hundred " + words : words;
if(len == 3) {
return words;
}
var thousand = convert_to_word(str.slice(0, len-3), false);
words = thousand != undefined ? thousand + " thousand " + words : words;
if(len <= 5) {
return words;
}
var lakh = convert_to_word(str.slice(0, len-5), false);
words = lakh != undefined ? lakh + " lakh " + words : words;
if(len <= 7) {
return words;
}
recursive_call_count = recursive_call_count + 1;
return get_rupees_in_words(str.slice(0, len-7), recursive_call_count) + " crore " + words;
}
Please check out my code pen
If anybody ever wants to do this but in Spanish (en español), here's my code based on Hardik's
function num2str(num, moneda) {
moneda = moneda || (num !== 1 ? "pesos" : "peso");
var fraction = Math.round(__cf_frac(num) * 100);
var f_text = " (" + pad(fraction, 2) + "/100 M.N.)";
return __cf_convert_number(num) + " " + moneda + f_text;
}
function __cf_frac(f) {
return f % 1;
}
function __cf_convert_number(number) {
if ((number < 0) || (number > 999999999)) {
throw Error("N\u00famero fuera de rango");
}
var millon = Math.floor(number / 1000000);
number -= millon * 1000000;
var cientosDeMiles = Math.floor(number / 100000);
number -= cientosDeMiles * 100000;
var miles = Math.floor(number / 1000);
number -= miles * 1000;
var centenas = Math.floor(number / 100);
number = number % 100;
var tn = Math.floor(number / 10);
var one = Math.floor(number % 10);
var res = "";
var cientos = Array("", "cien", "doscientos", "trescientos", "cuatrocientos", "quinientos", "seiscientos", "setecientos", "ochocientos", "novecientos");
if (millon > 0) {
res += (__cf_convert_number(millon) + (millon === 1 ? " mill\u00f3n" : " millones"));
}
if (cientosDeMiles > 0) {
res += (((res == "") ? "" : " ") +
cientos[cientosDeMiles] + (miles > 0 || centenas > 0 || tn > 0 || one < 0 ? (cientosDeMiles == 1 ? "to " : " ") : ""));
}
if (miles > 0) {
res += (((res == "") ? "" : " ") +
__cf_convert_number(miles) + " mil");
}
if (centenas) {
res += (((res == "") ? "" : " ") +
cientos[centenas] + (tn > 0 || one > 0 ? (centenas > 1 ? " " : "to ") : ""));
}
var ones = Array("", "un", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve");
var tens = Array("", "", "veinte", "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", "noventa");
if (tn > 0 || one > 0) {
if (tn < 2) {
res += ones[tn * 10 + one];
}
else {
if (tn === 2 && one > 0)
res += "veinti" + ones[one];
else {
res += tens[tn];
if (one > 0) {
res += (" y " + ones[one]);
}
}
}
}
if (res == "") {
res = "cero";
}
return res.replace(" ", " ");
}
function pad(num, largo, char) {
char = char || '0';
num = num + '';
return num.length >= largo ? num : new Array(largo - num.length + 1).join(char) + num;
}
Result:
num2str(123456789)
"ciento veintitres millones cuatrocientos cincuenta y seis mil setecientos ochenta y nueve pesos (00/100 M.N.)"
I am providing here my solution for converting numbers to the equivalent English words using the Single Loop String Triplets (SLST) Method which I have published and explained in detail here at Code Review with illustration graphics.
Simple Number to Words using a Single Loop String Triplets in JavaScript
The concept is simple and easily coded and is also very efficient and fast. The code is very short compared with other alternative methods described in this article.
The concept also permits the conversion of very vary large numbers as it does not rely on using the numeric/math function of the language and therefore avoids any limitations.
The Scale Array may be increased by adding more scale names if required after "Decillion".
A sample test function is provided below to generate numbers from 1 to 1099 as an example.
A full fancy version is available that caters for adding the word "and" and commas between the scales and numbers to align with the UK and US ways of spelling the numbers.
Hope this is useful.
/************************************************************/
function NumToWordsInt(NumIn) {
/************************************************************
* Convert Integer Numbers to English Words
* Using the Single Loop String Triplets Method
* #Param : {Number} The number to be converted
* For large numbers use a string
* #Return: {String} Wordified Number (Number in English Words)
* #Author: Mohsen Alyafei 10 July 2019
* #Notes : Call separately for whole and for fractional parts.
* Scale Array may be increased by adding more scale
* names if required after Decillion.
/************************************************************/
if (NumIn==0) return "Zero";
var Ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"],
Tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"],
Scale = ["", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion"],
N1, N2, Sep, j, i, h, Trplt, tns="", NumAll = "";
NumIn += ""; // Make NumIn a String
//----------------- code starts -------------------
NumIn = "0".repeat(NumIn.length * 2 % 3) + NumIn; //Create shortest string triplets 0 padded
j = 0; //Start with the highest triplet from LH
for (i = NumIn.length / 3 - 1; i >= 0; i--) { //Loop thru number of triplets from LH most
Trplt = NumIn.substring(j, j + 3); //Get a triplet number starting from LH
if (Trplt !="000") { //Skip empty trplets
Sep = Trplt[2] !="0" ? "-":" "; //Dash only for 21 to 99
N1 = Number(Trplt[0]); //Get Hundreds digit
N2 = Number(Trplt.substr(1)); //Get 2 lowest digits (00 to 99)
tns = N2 > 19 ? Tens[Number(Trplt[1])] + Sep + Ones[Number(Trplt[2])] : Ones[N2];
NumAll += ((h = N1>0 ? Ones[N1] + " Hundred": "") + " " + tns).trim() + " " + Scale[i]+ " ";
}
j += 3; //Next lower triplets (move to RH)
}
//----------------- code Ends --------------------
return NumAll.trim(); //Return trimming excess spaces if any
}
// ----------------- test sample -----------------
console.log(NumToWordsInt(67123))
console.log(NumToWordsInt(120003123))
console.log(NumToWordsInt(123999))
console.log(NumToWordsInt(789123))
console.log(NumToWordsInt(100178912))
console.log(NumToWordsInt(777))
console.log(NumToWordsInt(999999999))
console.log(NumToWordsInt(45))
I know this has been answered but I had been working on this before seeing the question. Doesn't have some small errors found in other answers. Supports up to vigintillion.
const num_text = num => {
const ones = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine"}, _tens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"], tens = {2: "twenty", 3: "thirty", 4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety"}, above_tens = ["thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion"];
var result = [];
if (/^0+$/g.test(num)) return "zero";
num = num.replace(/^0+/g, "").split(/(?=(?:...)*$)/);
for (var count = 0; count < num.length; count++){
var _result = "", _num = num[count];
_num = _num.replace(/^0+/g, "");
if (_num.length == 3){
_result += ones[_num[0]] + " hundred";
_num = _num.substring(1, 3).replace(/^0+/g, "");
if (_num.length > 0) _result += " and ";
}
if (_num.length == 1){
_result += ones[_num];
}else if (_num.length == 2){
if (_num[0] == "1"){
_result += _tens[_num[1]];
}else if (/.0/g.test(_num)){
_result += tens[_num[0]];
}else{
_result += tens[_num[0]] + " " + ones[_num[1]];
}
}
if (_result != ""){
if (num.length - count - 2 >= 0) _result += " " + above_tens[num.length - count - 2];
result.push(_result);
}
}
if (result[result.length - 1].includes("and") || result.length == 1) return result.join(", ");
return result.slice(0, result.length - 1).join(", ") + " and " + result[result.length - 1];
}
<input id="input">
<button onclick="document.getElementById('result').innerHTML = num_text(document.getElementById('input').value)">Convert</button>
<div id="result"></div>
https://stackoverflow.com/a/69243038/8784402
TypeScript Version Based on ES2022 + Fastest
Test on Typescript Playground
Hindi Version
class N2WHindi {
// "शून्य"
private static readonly zeroTo99: string[] =
'|एक|दो|तीन|चार|पाँच|छः|सात|आठ|नौ|दश|ग्यारह|बारह|तेरह|चौदह|पन्द्रह|सोलह|सत्रह|अठारह|उन्नीस|बीस|इक्कीस|बाईस|तेईस|चौबीस|पच्चीस|छब्बीस|सत्ताईस|अट्ठाईस|उनतीस|तीस|इकतीस|बत्तीस|तैंतीस|चौंतीस|पैंतीस|छत्तीस|सैंतीस|अड़तीस|उनतालीस|चालीस|इकतालीस|बयालीस|तैंतालीस|चौवालीस|पैंतालीस|छियालीस|सैंतालीस|अड़तालीस|उनचास|पचास|इक्यावन|बावन|तिरपन|चौवन|पचपन|छप्पन|सत्तावन|अट्ठावन|उनसठ|साठ|इकसठ|बासठ|तिरसठ|चौंसठ|पैंसठ|छियासठ|सड़सठ|अड़सठ|उनहत्तर|सत्तर|इकहत्तर|बहत्तर|तिहत्तर|चौहत्तर|पचहत्तर|छिहत्तर|सतहत्तर|अठहत्तर|उन्यासी|अस्सी|इक्यासी|बयासी|तिरासी|चौरासी|पचासी|छियासी|सत्तासी|अट्ठासी|नवासी|नब्बे|इक्यानबे|बानबे|तिरानबे|चौरानबे|पंचानबे|छियानबे|सत्तानबे|अट्ठानबे|निन्यान्बे'.split(
'|'
);
private static readonly place: string[] = 'हज़ार|लाख|करोड़|अरब|खरब|नील'.split('|');
public static convert(x: string): string {
let n: number = x.length;
x = n == 0 ? '00' : n == 1 || n % 2 == 0 ? '0' + x : x;
n = x.length;
let r: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n > 0) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' सौ ' + r;
}
for (let i = 0; n > 0; i++) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WHindi.place[i] + (r ? ' ' + r : '');
}
return r;
}
}
Indian English Version
class N2WIndian {
private static readonly zeroTo99: string[] = [];
private static readonly place: string[] = 'Thousand|Lakh|Crore|Arab|Kharab|Nil'.split('|');
static {
const ones: string[] =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens: string[] = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t: number = Math.floor(i / 10);
const o: number = i % 10;
N2WIndian.zeroTo99.push(t < 2 ? ones[i] : tens[t] + (o ? ' ' + ones[o] : ''));
}
}
public static convert(x: string): string {
let n: number = x.length;
x = n == 0 ? '00' : n == 1 || n % 2 == 0 ? '0' + x : x;
n = x.length;
let r = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n >= 1) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' Hundred ' + r;
}
for (let i = 0; n > 0; i++) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WIndian.place[i] + (r ? ' ' + r : '');
}
return r;
}
}
International Version
class N2WIntl {
private static readonly zeroTo999: string[] = [];
private static readonly place =
'|Thousand|Million|Billion|Trillion|Quadrillion|Quintillion|Sextillion|Septillion|Octillion|Nonillion|Decillion|Undecillion|Duodecillion|Tredecillion|Quattuordecillion|Quindecillion|Sedecillion|Septendecillion|Octodecillion|Novendecillion|Vigintillion|Unvigintillion|Duovigintillion|Tresvigintillion|Quattuorvigintillion|Quinvigintillion|Sesvigintillion|Septemvigintillion|Octovigintillion|Novemvigintillion|Trigintillion|Untrigintillion|Duotrigintillion|Trestrigintillion|Quattuortrigintillion|Quintrigintillion|Sestrigintillion|Septentrigintillion|Octotrigintillion|Noventrigintillion|Quadragintillion'.split(
'|'
);
static {
const ones =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t = Math.floor(i / 10);
const o = i % 10;
N2WIntl.zeroTo999[i] = t < 2 ? ones[i] : tens[t] + (o == 0 ? '' : ' ' + ones[o]);
}
for (let i = 100; i < 1000; i++) {
const h = Math.floor(i / 100);
const t = Math.floor(i / 10) % 10;
const o = i % 10;
const r = N2WIntl.zeroTo999[h] + ' Hundred';
N2WIntl.zeroTo999[i] = t == 0 && o == 0 ? r : r + ' ' + N2WIntl.zeroTo999[t * 10 + o];
}
}
public static convert(x: string): string {
let n = x.length;
x = n == 0 ? '000' : ((n % 3 === 1) ? '00' : (n % 3 === 2) ? '0' : '') + x;
n = x.length;
let r: string = '';
for (let i = 0; n > 0; i++) {
const v: string =
N2WIntl.zeroTo999[x.charCodeAt((n -= 3)) * 100 + x.charCodeAt(n + 1) * 10 + x.charCodeAt(n + 2) - 5328];
if (v) r = v + (i ? ' ' + N2WIntl.place[i] : '') + (r ? ' ' + r : '');
}
return r;
}
}
const test = () => {
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WHindi.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WHindi.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIndian.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WIndian.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIntl.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^126 -1 :\n' + '9'.repeat(126) + '\n' + N2WIntl.convert('9'.repeat(126)));
}
};
test();
Example to convert currency
const [r, p] = "23.54".split('.');
console.log(`${N2WHindi.convert(r)} रुपया और ${N2WHindi.convert(p)} पैसा`)
console.log(`${N2WIndian.convert(r)} Rupees and ${N2WIndian.convert(p)} Paisa`)
console.log(`${N2WIntl.convert(r)} Dollars and ${N2WIntl.convert(p)} Cents`)
I think this will help you
aTens = [ "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy","Eighty", "Ninety"];
aOnes = [ "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ];
var aUnits = "Thousand";
function convertnumbertostring(){
var num=prompt('','enter the number');
var j=6;
if(num.length<j){
var y = ConvertToWords(num);
alert(y);
}else{
alert('Enter the number of 5 letters')
}
};
function ConvertToHundreds(num)
{
var cNum, nNum;
var cWords = "";
if (num > 99) {
/* Hundreds. */
cNum = String(num);
nNum = Number(cNum.charAt(0));
cWords += aOnes[nNum] + " Hundred";
num %= 100;
if (num > 0){
cWords += " and "
}
}
if (num > 19) {
/* Tens. */
cNum = String(num);
nNum = Number(cNum.charAt(0));
cWords += aTens[nNum - 2];
num %= 10;
if (num > 0){
cWords += "-";
}
}
if (num > 0) {
/* Ones and teens. */
nNum = Math.floor(num);
cWords += aOnes[nNum];
}
return(cWords);
}
function ConvertToWords(num)
{
var cWords;
for (var i = 0; num > 0; i++) {
if (num % 1000 > 0) {
if (i != 0){
cWords = ConvertToHundreds(num) + " " + aUnits + " " + cWords;
}else{
cWords = ConvertToHundreds(num) + " ";
}
}
num = (num / 1000);
}
return(cWords);
}

Vue Filter To Convert Amount in Numbers to Amount in Words [duplicate]

I'm writing some code that converts a given number into words, here's what I have got after googling. But I think it's a bit too long for such a simple task.
Two Regular Expressions and two for loops, I want something simpler.
I am trying to achieve this in as few lines of code as possible. here's what I've come up with so far:
Any suggestions?
var th = ['','thousand','million', 'billion','trillion'];
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g,'');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1)
x = s.length;
if (x > 15)
return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i=0; i < x; i++) {
if ((x-i)%3==2) {
if (n[i] == '1') {
str += tn[Number(n[i+1])] + ' ';
i++;
sk=1;
} else if (n[i]!=0) {
str += tw[n[i]-2] + ' ';
sk=1;
}
} else if (n[i]!=0) { // 0235
str += dg[n[i]] +' ';
if ((x-i)%3==0) str += 'hundred ';
sk=1;
}
if ((x-i)%3==1) {
if (sk)
str += th[(x-i-1)/3] + ' ';
sk=0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i=x+1; i<y; i++)
str += dg[n[i]] +' ';
}
return str.replace(/\s+/g,' ');
}
Also, the above code converts to the English numbering system like Million/Billion, I need the South Asian numbering system, like in Lakhs and Crores.
Update: Looks like this is more useful than I thought. I've just published this on npm. https://www.npmjs.com/package/num-words
Here's a shorter code. with one RegEx and no loops. converts as you wanted, in south asian numbering system
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function inWords (num) {
if ((num = num.toString()).length > 9) return 'overflow';
n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
if (!n) return; var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';
return str;
}
document.getElementById('number').onkeyup = function () {
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
<span id="words"></span>
<input id="number" type="text" />
The only limitation is, you can convert maximum of 9 digits, which I think is more than sufficient in most cases..
"Deceptively simple task." – Potatoswatter
Indeed. There's many little devils hanging out in the details of this problem. It was very fun to solve tho.
EDIT: This update takes a much more compositional approach. Previously there was one big function which wrapped a couple other proprietary functions. Instead, this time we define generic reusable functions which could be used for many varieties of tasks. More about those after we take a look at numToWords itself …
// numToWords :: (Number a, String a) => a -> String
let numToWords = n => {
let a = [
'', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
let b = [
'', '', 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
let g = [
'', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'
];
// this part is really nasty still
// it might edit this again later to show how Monoids could fix this up
let makeGroup = ([ones,tens,huns]) => {
return [
num(huns) === 0 ? '' : a[huns] + ' hundred ',
num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '',
a[tens+ones] || a[ones]
].join('');
};
// "thousands" constructor; no real good names for this, i guess
let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`;
// execute !
if (typeof n === 'number') return numToWords(String(n));
if (n === '0') return 'zero';
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(comp(not)(isEmpty))
.reverse()
.join(' ');
};
Here are the dependencies:
You'll notice these require next to no documentation because their intents are immediately clear. chunk might be the only one that takes a moment to digest, but it's really not too bad. Plus the function name gives us a pretty good indication what it does, and it's probably a function we've encountered before.
const arr = x => Array.from(x);
const num = x => Number(x) || 0;
const str = x => String(x);
const isEmpty = xs => xs.length === 0;
const take = n => xs => xs.slice(0,n);
const drop = n => xs => xs.slice(n);
const reverse = xs => xs.slice(0).reverse();
const comp = f => g => x => f (g (x));
const not = x => !x;
const chunk = n => xs =>
isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];
"So these make it better?"
Look at how the code has cleaned up significantly
// NEW CODE (truncated)
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(comp(not)(isEmpty))
.reverse()
.join(' ');
// OLD CODE (truncated)
let grp = n => ('000' + n).substr(-3);
let rem = n => n.substr(0, n.length - 3);
let cons = xs => x => g => x ? [x, g && ' ' + g || '', ' ', xs].join('') : xs;
let iter = str => i => x => r => {
if (x === '000' && r.length === 0) return str;
return iter(cons(str)(fmt(x))(g[i]))
(i+1)
(grp(r))
(rem(r));
};
return iter('')(0)(grp(String(n)))(rem(String(n)));
Most importantly, the utility functions we added in the new code can be used other places in your app. This means that, as a side effect of implementing numToWords in this way, we get the other functions for free. Bonus soda !
Some tests
console.log(numToWords(11009));
//=> eleven thousand nine
console.log(numToWords(10000001));
//=> ten million one
console.log(numToWords(987));
//=> nine hundred eighty-seven
console.log(numToWords(1015));
//=> one thousand fifteen
console.log(numToWords(55111222333));
//=> fifty-five billion one hundred eleven million two hundred
// twenty-two thousand three hundred thirty-three
console.log(numToWords("999999999999999999999991"));
//=> nine hundred ninety-nine sextillion nine hundred ninety-nine
// quintillion nine hundred ninety-nine quadrillion nine hundred
// ninety-nine trillion nine hundred ninety-nine billion nine
// hundred ninety-nine million nine hundred ninety-nine thousand
// nine hundred ninety-one
console.log(numToWords(6000753512));
//=> six billion seven hundred fifty-three thousand five hundred
// twelve
Runnable demo
const arr = x => Array.from(x);
const num = x => Number(x) || 0;
const str = x => String(x);
const isEmpty = xs => xs.length === 0;
const take = n => xs => xs.slice(0,n);
const drop = n => xs => xs.slice(n);
const reverse = xs => xs.slice(0).reverse();
const comp = f => g => x => f (g (x));
const not = x => !x;
const chunk = n => xs =>
isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];
// numToWords :: (Number a, String a) => a -> String
let numToWords = n => {
let a = [
'', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
let b = [
'', '', 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
let g = [
'', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'
];
// this part is really nasty still
// it might edit this again later to show how Monoids could fix this up
let makeGroup = ([ones,tens,huns]) => {
return [
num(huns) === 0 ? '' : a[huns] + ' hundred ',
num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '',
a[tens+ones] || a[ones]
].join('');
};
let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`;
if (typeof n === 'number')
return numToWords(String(n));
else if (n === '0')
return 'zero';
else
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(comp(not)(isEmpty))
.reverse()
.join(' ');
};
console.log(numToWords(11009));
//=> eleven thousand nine
console.log(numToWords(10000001));
//=> ten million one
console.log(numToWords(987));
//=> nine hundred eighty-seven
console.log(numToWords(1015));
//=> one thousand fifteen
console.log(numToWords(55111222333));
//=> fifty-five billion one hundred eleven million two hundred
// twenty-two thousand three hundred thirty-three
console.log(numToWords("999999999999999999999991"));
//=> nine hundred ninety-nine sextillion nine hundred ninety-nine
// quintillion nine hundred ninety-nine quadrillion nine hundred
// ninety-nine trillion nine hundred ninety-nine billion nine
// hundred ninety-nine million nine hundred ninety-nine thousand
// nine hundred ninety-one
console.log(numToWords(6000753512));
//=> six billion seven hundred fifty-three thousand five hundred
// twelve
You can transpile the code using babel.js if you want to see the ES5 variant
I spent a while developing a better solution to this. It can handle very big numbers but once they get over 16 digits you have pass the number in as a string. Something about the limit of JavaScript numbers.
function numberToEnglish( n ) {
var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g,"");
/* Is number zero? */
if( parseInt( string ) === 0 ) {
return 'zero';
}
/* Array of units as words */
units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
/* Array of tens as words */
tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
/* Array of scales as words */
scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
/* Split user argument into 3 digit chunks from right to left */
start = string.length;
chunks = [];
while( start > 0 ) {
end = start;
chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
}
/* Check if function has enough scale words to be able to stringify the user argument */
chunksLen = chunks.length;
if( chunksLen > scales.length ) {
return '';
}
/* Stringify each integer in each chunk */
words = [];
for( i = 0; i < chunksLen; i++ ) {
chunk = parseInt( chunks[i] );
if( chunk ) {
/* Split chunk into array of individual integers */
ints = chunks[i].split( '' ).reverse().map( parseFloat );
/* If tens integer is 1, i.e. 10, then add 10 to units integer */
if( ints[1] === 1 ) {
ints[0] += 10;
}
/* Add scale word if chunk is not zero and array item exists */
if( ( word = scales[i] ) ) {
words.push( word );
}
/* Add unit word if array item exists */
if( ( word = units[ ints[0] ] ) ) {
words.push( word );
}
/* Add tens word if array item exists */
if( ( word = tens[ ints[1] ] ) ) {
words.push( word );
}
/* Add 'and' string after units or tens integer if: */
if( ints[0] || ints[1] ) {
/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
if( ints[2] || ! i && chunksLen ) {
words.push( and );
}
}
/* Add hundreds word if array item exists */
if( ( word = units[ ints[2] ] ) ) {
words.push( word + ' hundred' );
}
}
}
return words.reverse().join( ' ' );
}
// - - - - - Tests - - - - - -
function test(v) {
var sep = ('string'==typeof v)?'"':'';
console.log("numberToEnglish("+sep + v.toString() + sep+") = "+numberToEnglish(v));
}
test(2);
test(721);
test(13463);
test(1000001);
test("21,683,200,000,621,384");
You might want to try it recursive. It works for numbers between 0 and 999999. Keep in mind that (~~) does the same as Math.floor
var num = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split(" ");
var tens = "twenty thirty forty fifty sixty seventy eighty ninety".split(" ");
function number2words(n){
if (n < 20) return num[n];
var digit = n%10;
if (n < 100) return tens[~~(n/10)-2] + (digit? "-" + num[digit]: "");
if (n < 1000) return num[~~(n/100)] +" hundred" + (n%100 == 0? "": " " + number2words(n%100));
return number2words(~~(n/1000)) + " thousand" + (n%1000 != 0? " " + number2words(n%1000): "");
}
I like the result I got here which i think is easy to read and short enough to fit as a solution.
function NumInWords (number) {
const first = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
const tens = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
const mad = ['', 'thousand', 'million', 'billion', 'trillion'];
let word = '';
for (let i = 0; i < mad.length; i++) {
let tempNumber = number%(100*Math.pow(1000,i));
if (Math.floor(tempNumber/Math.pow(1000,i)) !== 0) {
if (Math.floor(tempNumber/Math.pow(1000,i)) < 20) {
word = first[Math.floor(tempNumber/Math.pow(1000,i))] + mad[i] + ' ' + word;
} else {
word = tens[Math.floor(tempNumber/(10*Math.pow(1000,i)))] + '-' + first[Math.floor(tempNumber/Math.pow(1000,i))%10] + mad[i] + ' ' + word;
}
}
tempNumber = number%(Math.pow(1000,i+1));
if (Math.floor(tempNumber/(100*Math.pow(1000,i))) !== 0) word = first[Math.floor(tempNumber/(100*Math.pow(1000,i)))] + 'hunderd ' + word;
}
return word;
}
console.log(NumInWords(89754697976431))
And the result is :
eighty-nine trillion seven hundred fifty-four billion six hundred ninety-seven million nine hundred seventy-six thousand four hundred thirty-one
<html>
<head>
<title>HTML - Convert numbers to words using JavaScript</title>
<script type="text/javascript">
function onlyNumbers(evt) {
var e = event || evt; // For trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function NumToWord(inputNumber, outputControl) {
var str = new String(inputNumber)
var splt = str.split("");
var rev = splt.reverse();
var once = ['Zero', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'];
var twos = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
var tens = ['', 'Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];
numLength = rev.length;
var word = new Array();
var j = 0;
for (i = 0; i < numLength; i++) {
switch (i) {
case 0:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = '' + once[rev[i]];
}
word[j] = word[j];
break;
case 1:
aboveTens();
break;
case 2:
if (rev[i] == 0) {
word[j] = '';
}
else if ((rev[i - 1] == 0) || (rev[i - 2] == 0)) {
word[j] = once[rev[i]] + " Hundred ";
}
else {
word[j] = once[rev[i]] + " Hundred and";
}
break;
case 3:
if (rev[i] == 0 || rev[i + 1] == 1) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if ((rev[i + 1] != 0) || (rev[i] > 0)) {
word[j] = word[j] + " Thousand";
}
break;
case 4:
aboveTens();
break;
case 5:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if (rev[i + 1] !== '0' || rev[i] > '0') {
word[j] = word[j] + " Lakh";
}
break;
case 6:
aboveTens();
break;
case 7:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if (rev[i + 1] !== '0' || rev[i] > '0') {
word[j] = word[j] + " Crore";
}
break;
case 8:
aboveTens();
break;
// This is optional.
// case 9:
// if ((rev[i] == 0) || (rev[i + 1] == 1)) {
// word[j] = '';
// }
// else {
// word[j] = once[rev[i]];
// }
// if (rev[i + 1] !== '0' || rev[i] > '0') {
// word[j] = word[j] + " Arab";
// }
// break;
// case 10:
// aboveTens();
// break;
default: break;
}
j++;
}
function aboveTens() {
if (rev[i] == 0) { word[j] = ''; }
else if (rev[i] == 1) { word[j] = twos[rev[i - 1]]; }
else { word[j] = tens[rev[i]]; }
}
word.reverse();
var finalOutput = '';
for (i = 0; i < numLength; i++) {
finalOutput = finalOutput + word[i];
}
document.getElementById(outputControl).innerHTML = finalOutput;
}
</script>
</head>
<body>
<h1>
HTML - Convert numbers to words using JavaScript</h1>
<input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);" onkeyup="NumToWord(this.value,'divDisplayWords');"
maxlength="9" style="background-color: #efefef; border: 2px solid #CCCCC; font-size: large" />
<br />
<br />
<div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;">
</div>
</body>
</html>
I modified MC Shaman's code to fix the bug of single number having and appear before it
function numberToEnglish( n ) {
var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g,"");
/* Is number zero? */
if( parseInt( string ) === 0 ) {
return 'zero';
}
/* Array of units as words */
units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
/* Array of tens as words */
tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
/* Array of scales as words */
scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
/* Split user argument into 3 digit chunks from right to left */
start = string.length;
chunks = [];
while( start > 0 ) {
end = start;
chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
}
/* Check if function has enough scale words to be able to stringify the user argument */
chunksLen = chunks.length;
if( chunksLen > scales.length ) {
return '';
}
/* Stringify each integer in each chunk */
words = [];
for( i = 0; i < chunksLen; i++ ) {
chunk = parseInt( chunks[i] );
if( chunk ) {
/* Split chunk into array of individual integers */
ints = chunks[i].split( '' ).reverse().map( parseFloat );
/* If tens integer is 1, i.e. 10, then add 10 to units integer */
if( ints[1] === 1 ) {
ints[0] += 10;
}
/* Add scale word if chunk is not zero and array item exists */
if( ( word = scales[i] ) ) {
words.push( word );
}
/* Add unit word if array item exists */
if( ( word = units[ ints[0] ] ) ) {
words.push( word );
}
/* Add tens word if array item exists */
if( ( word = tens[ ints[1] ] ) ) {
words.push( word );
}
/* Add 'and' string after units or tens integer if: */
if( ints[0] || ints[1] ) {
/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
if( ints[2] || (i + 1) > chunksLen ) {
words.push( and );
}
}
/* Add hundreds word if array item exists */
if( ( word = units[ ints[2] ] ) ) {
words.push( word + ' hundred' );
}
}
}
return words.reverse().join( ' ' );
}
// - - - - - Tests - - - - - -
function figure(val) {
finalFig = numberToEnglish(val);
document.getElementById("words").innerHTML = finalFig;
}
<span id="words"></span>
<input id="number" type="text" onkeyup=figure(this.value) />
Update February 2021
Although this question is raised over 8 years ago with various solutions and answers, the easiest solution that can be easily updated to increase the scale by just inserting a name in the array without code modification; and also using very short code is the function below.
This solution is for the English reading of numbers (not the South-Asian System) and uses the standard US English (American way) of writing large numbers. i.e. it does not use the UK System (the UK system uses the word "and" like: "three hundred and twenty-two thousand").
Test cases are provided and also an input field.
Remember, it is "Unsigned Integers" that we are converting to words.
You can increase the scale[] array beyond Sextillion.
As the function is short, you can use it as an internal function in, say, currency conversion where decimal numbers are used and call it twice for the whole part and the fractional part.
Hope it is useful.
/********************************************************
* #function : integerToWords()
* #purpose : Converts Unsigned Integers to Words
* Using String Triplet Array.
* #version : 1.05
* #author : Mohsen Alyafei
* #date : 15 January 2021
* #param : {number} [integer numeric or string]
* #returns : {string} The wordified number string
********************************************************/
const Ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
Tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety","Hundred"],
Scale = ["","Thousand","Million","Billion","Trillion","Quadrillion","Quintillion","Sextillion"];
//==================================
const integerToWords = (n = 0) => {
if (n == 0) return "Zero"; // check for zero
n = ("0".repeat(2*(n+="").length % 3) + n).match(/.{3}/g); // create triplets array
if (n.length > Scale.length) return "Too Large"; // check if larger than scale array
let out= ""; return n.forEach((Triplet,pos) => { // loop into array for each triplet
if (+Triplet) { out+=' ' +(+Triplet[0] ? Ones[+Triplet[0]]+' '+ Tens[10] : "") +
' ' + (+Triplet.substr(1)< 20 ? Ones[+Triplet.substr(1)] :
Tens[+Triplet[1]] + (+Triplet[2] ? "-" : "") + Ones[+Triplet[2]]) +
' ' + Scale[n.length-pos-1]; }
}),out.replace(/\s+/g,' ').trim();}; // lazy job using trim()
//==================================
//=========================================
// Test Cases
//=========================================
var r=0; // test tracker
r |= test(0,"Zero");
r |= test(5,"Five");
r |= test(10,"Ten");
r |= test(19,"Nineteen");
r |= test(33,"Thirty-Three");
r |= test(100,"One Hundred");
r |= test(111,"One Hundred Eleven");
r |= test(890,"Eight Hundred Ninety");
r |= test(1234,"One Thousand Two Hundred Thirty-Four");
r |= test(12345,"Twelve Thousand Three Hundred Forty-Five");
r |= test(123456,"One Hundred Twenty-Three Thousand Four Hundred Fifty-Six");
r |= test(1234567,"One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven");
r |= test(12345678,"Twelve Million Three Hundred Forty-Five Thousand Six Hundred Seventy-Eight");
r |= test(123456789,"One Hundred Twenty-Three Million Four Hundred Fifty-Six Thousand Seven Hundred Eighty-Nine");
r |= test(1234567890,"One Billion Two Hundred Thirty-Four Million Five Hundred Sixty-Seven Thousand Eight Hundred Ninety");
r |= test(1001,"One Thousand One");
r |= test(10001,"Ten Thousand One");
r |= test(100001,"One Hundred Thousand One");
r |= test(1000001,"One Million One");
r |= test(10000001,"Ten Million One");
r |= test(100000001,"One Hundred Million One");
r |= test(12012,"Twelve Thousand Twelve");
r |= test(120012,"One Hundred Twenty Thousand Twelve");
r |= test(1200012,"One Million Two Hundred Thousand Twelve");
r |= test(12000012,"Twelve Million Twelve");
r |= test(120000012,"One Hundred Twenty Million Twelve");
r |= test(75075,"Seventy-Five Thousand Seventy-Five");
r |= test(750075,"Seven Hundred Fifty Thousand Seventy-Five");
r |= test(7500075,"Seven Million Five Hundred Thousand Seventy-Five");
r |= test(75000075,"Seventy-Five Million Seventy-Five");
r |= test(750000075,"Seven Hundred Fifty Million Seventy-Five");
r |= test(1000,"One Thousand");
r |= test(1000000,"One Million");
r |= test(1000000000,"One Billion");
r |= test(1000000000000,"One Trillion");
r |= test("1000000000000000","One Quadrillion");
r |= test("1000000000000000000","One Quintillion");
r |= test("1000000100100100100","One Quintillion One Hundred Billion One Hundred Million One Hundred Thousand One Hundred");
if (r==0) console.log("All Tests Passed.");
//=====================================
// Tester Function
//=====================================
function test(n,should) {
let result = integerToWords(n);
if (result !== should) {console.log(`${n} Output : ${result}\n${n} Should be: ${should}`);return 1;}
}
<input type="text" name="number" placeholder="Please enter an Integer Number" onkeyup="word.innerHTML=integerToWords(this.value)" />
<div id="word"></div>
TypeScript Version Based on ES2022 + Fastest
Test on Typescript Playground
Hindi Version
class N2WHindi {
private static readonly zeroTo99: string[] =
'|एक|दो|तीन|चार|पाँच|छः|सात|आठ|नौ|दश|ग्यारह|बारह|तेरह|चौदह|पन्द्रह|सोलह|सत्रह|अठारह|उन्नीस|बीस|इक्कीस|बाईस|तेईस|चौबीस|पच्चीस|छब्बीस|सत्ताईस|अट्ठाईस|उनतीस|तीस|इकतीस|बत्तीस|तैंतीस|चौंतीस|पैंतीस|छत्तीस|सैंतीस|अड़तीस|उनतालीस|चालीस|इकतालीस|बयालीस|तैंतालीस|चौवालीस|पैंतालीस|छियालीस|सैंतालीस|अड़तालीस|उनचास|पचास|इक्यावन|बावन|तिरपन|चौवन|पचपन|छप्पन|सत्तावन|अट्ठावन|उनसठ|साठ|इकसठ|बासठ|तिरसठ|चौंसठ|पैंसठ|छियासठ|सड़सठ|अड़सठ|उनहत्तर|सत्तर|इकहत्तर|बहत्तर|तिहत्तर|चौहत्तर|पचहत्तर|छिहत्तर|सतहत्तर|अठहत्तर|उन्यासी|अस्सी|इक्यासी|बयासी|तिरासी|चौरासी|पचासी|छियासी|सत्तासी|अट्ठासी|नवासी|नब्बे|इक्यानबे|बानबे|तिरानबे|चौरानबे|पंचानबे|छियानबे|सत्तानबे|अट्ठानबे|निन्यान्बे'.split(
'|'
);
private static readonly place: string[] = 'हज़ार|लाख|करोड़|अरब|खरब|नील'.split('|');
public static convert(x: string): string {
let n: number = x.length;
x = n === 0 ? '00' : n === 1 || n % 2 === 0 ? '0' + x : x;
n = x.length;
let r: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n > 0) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' सौ' + (r ? ' ' + r : '');
}
for (let i = 0; n > 0; i++) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WHindi.place[i] + (r ? ' ' + r : '');
}
return r || 'शून्य';
}
}
Indian English Version
class N2WIndian {
private static readonly zeroTo99: string[] = [];
private static readonly place: string[] = 'Thousand|Lakh|Crore|Arab|Kharab|Nil'.split('|');
static {
const ones: string[] =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens: string[] = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t: number = Math.floor(i / 10);
const o: number = i % 10;
N2WIndian.zeroTo99.push(t < 2 ? ones[i] : tens[t] + (o ? ' ' + ones[o] : ''));
}
}
public static convert(x: string): string {
let n: number = x.length;
x = n === 0 ? '00' : n === 1 || n % 2 === 0 ? '0' + x : x;
n = x.length;
let r = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n >= 1) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' Hundred' + (r ? ' ' + r : '');
}
for (let i = 0; n > 0; i++) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WIndian.place[i] + (r ? ' ' + r : '');
}
return r || 'Zero';
}
}
International Version
class N2WIntl {
private static readonly zeroTo999: string[] = [];
private static readonly place =
'|Thousand|Million|Billion|Trillion|Quadrillion|Quintillion|Sextillion|Septillion|Octillion|Nonillion|Decillion|Undecillion|Duodecillion|Tredecillion|Quattuordecillion|Quindecillion|Sedecillion|Septendecillion|Octodecillion|Novendecillion|Vigintillion|Unvigintillion|Duovigintillion|Tresvigintillion|Quattuorvigintillion|Quinvigintillion|Sesvigintillion|Septemvigintillion|Octovigintillion|Novemvigintillion|Trigintillion|Untrigintillion|Duotrigintillion|Trestrigintillion|Quattuortrigintillion|Quintrigintillion|Sestrigintillion|Septentrigintillion|Octotrigintillion|Noventrigintillion|Quadragintillion'.split(
'|'
);
static {
const ones =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t = Math.floor(i / 10);
const o = i % 10;
N2WIntl.zeroTo999[i] = t < 2 ? ones[i] : tens[t] + (o === 0 ? '' : ' ' + ones[o]);
}
for (let i = 100; i < 1000; i++) {
const h = Math.floor(i / 100);
const t = Math.floor(i / 10) % 10;
const o = i % 10;
const r = N2WIntl.zeroTo999[h] + ' Hundred';
N2WIntl.zeroTo999[i] = t === 0 && o === 0 ? r : r + ' ' + N2WIntl.zeroTo999[t * 10 + o];
}
}
public static convert(x: string): string {
let n = x.length;
x = n === 0 ? '000' : (n % 3 === 1 ? '00' : n % 3 === 2 ? '0' : '') + x;
n = x.length;
let r = '';
for (let i = 0; n > 0; i++) {
const v: string =
N2WIntl.zeroTo999[
x.charCodeAt((n -= 3)) * 100 + x.charCodeAt(n + 1) * 10 + x.charCodeAt(n + 2) - 5328
];
if (v) r = v + (i ? ' ' + N2WIntl.place[i] : '') + (r ? ' ' + r : '');
}
return r || 'Zero';
}
}
const test = () => {
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WHindi.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WHindi.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIndian.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WIndian.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIntl.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^126 -1 :\n' + '9'.repeat(126) + '\n' + N2WIntl.convert('9'.repeat(126)));
}
};
test();
Example
N2WHindi.convert('122356')
'एक लाख बाईस हज़ार तीन सौ छप्पन'
N2WIndian.convert('122356')
'One Lakh Twenty Two Thousand Three Hundred Fifty Six'
N2WIntl.convert('122356')
'One Hundred Twenty Two Thousand Three Hundred Fifty Six'
Example to convert currency
const [r, p] = "23.54".split('.');
`${N2WHindi.convert(r)} रुपया और ${N2WHindi.convert(p)} पैसा`
'तेईस रुपया और चौवन पैसा'
`${N2WIndian.convert(r)} Rupees and ${N2WIndian.convert(p)} Paisa`
'Twenty Three Rupees and Fifty Four Paisa'
`${N2WIntl.convert(r)} Dollars and ${N2WIntl.convert(p)} Cents`
'Twenty Three Dollars and Fifty Four Cents'
Converting the input string into a number rather than keeping it as a string, limits the solution to the maximum allowed float / integer value on that machine/browser. My script below handles currency up to 1 Trillion dollars - 1 cent :-). I can be extended to handle up to 999 Trillions by adding 3 or 4 lines of code.
var ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight",
"Nine","Ten","Eleven","Twelve","Thirteen","Fourteen",
"Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"];
var tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
"Eighty","Ninety"];
function words999(n999) { // n999 is an integer less than or equal to 999.
//
// Accept any 3 digit int incl 000 & 999 and return words.
//
var words = ''; var Hn = 0; var n99 = 0;
Hn = Math.floor(n999 / 100); // # of hundreds in it
if (Hn > 0) { // if at least one 100
words = words99(Hn) + " Hundred"; // one call for hundreds
}
n99 = n999 - (Hn * 100); // subtract the hundreds.
words += ((words == '')?'':' ') + words99(n99); // combine the hundreds with tens & ones.
return words;
} // function words999( n999 )
function words99(n99) { // n99 is an integer less than or equal to 99.
//
// Accept any 2 digit int incl 00 & 99 and return words.
//
var words = ''; var Dn = 0; var Un = 0;
Dn = Math.floor(n99 / 10); // # of tens
Un = n99 % 10; // units
if (Dn > 0 || Un > 0) {
if (Dn < 2) {
words += ones[Dn * 10 + Un]; // words for a # < 20
} else {
words += tens[Dn];
if (Un > 0) words += "-" + ones[Un];
}
} // if ( Dn > 0 || Un > 0 )
return words;
} // function words99( n99 )
function getAmtInWords(id1, id2) { // use numeric value of id1 to populate text in id2
//
// Read numeric amount field and convert into word amount
//
var t1 = document.getElementById(id1).value;
var t2 = t1.trim();
amtStr = t2.replace(/,/g,''); // $123,456,789.12 = 123456789.12
dotPos = amtStr.indexOf('.'); // position of dot before cents, -ve if it doesn't exist.
if (dotPos > 0) {
dollars = amtStr.slice(0,dotPos); // 1234.56 = 1234
cents = amtStr.slice(dotPos+1); // 1234.56 = .56
} else if (dotPos == 0) {
dollars = '0';
cents = amtStr.slice(dotPos+1); // 1234.56 = .56
} else {
dollars = amtStr.slice(0); // 1234 = 1234
cents = '0';
}
t1 = '000000000000' + dollars; // to extend to trillion, use 15 zeros
dollars = t1.slice(-12); // and -15 here.
billions = Number(dollars.substr(0,3));
millions = Number(dollars.substr(3,3));
thousands = Number(dollars.substr(6,3));
hundreds = Number(dollars.substr(9,3));
t1 = words999(billions); bW = t1.trim(); // Billions in words
t1 = words999(millions); mW = t1.trim(); // Millions in words
t1 = words999(thousands); tW = t1.trim(); // Thousands in words
t1 = words999(hundreds); hW = t1.trim(); // Hundreds in words
t1 = words99(cents); cW = t1.trim(); // Cents in words
var totAmt = '';
if (bW != '') totAmt += ((totAmt != '') ? ' ' : '') + bW + ' Billion';
if (mW != '') totAmt += ((totAmt != '') ? ' ' : '') + mW + ' Million';
if (tW != '') totAmt += ((totAmt != '') ? ' ' : '') + tW + ' Thousand';
if (hW != '') totAmt += ((totAmt != '') ? ' ' : '') + hW + ' Dollars';
if (cW != '') totAmt += ((totAmt != '') ? ' and ' : '') + cW + ' Cents';
// alert('totAmt = ' + totAmt); // display words in a alert
t1 = document.getElementById(id2).value;
t2 = t1.trim();
if (t2 == '') document.getElementById(id2).value = totAmt;
return false;
} // function getAmtInWords( id1, id2 )
// ======================== [ End Code ] ====================================
If you need with Cent then you may use this one
<script>
var iWords = ['zero', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine'];
var ePlace = ['ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen'];
var tensPlace = ['', ' ten', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety'];
var inWords = [];
var numReversed, inWords, actnumber, i, j;
function tensComplication() {
if (actnumber[i] == 0) {
inWords[j] = '';
} else if (actnumber[i] == 1) {
inWords[j] = ePlace[actnumber[i - 1]];
} else {
inWords[j] = tensPlace[actnumber[i]];
}
}
function convertAmount() {
var numericValue = document.getElementById('bdt').value;
numericValue = parseFloat(numericValue).toFixed(2);
var amount = numericValue.toString().split('.');
var taka = amount[0];
var paisa = amount[1];
document.getElementById('container').innerHTML = convert(taka) +" taka and "+ convert(paisa)+" paisa only";
}
function convert(numericValue) {
inWords = []
if(numericValue == "00" || numericValue =="0"){
return 'zero';
}
var obStr = numericValue.toString();
numReversed = obStr.split('');
actnumber = numReversed.reverse();
if (Number(numericValue) == 0) {
document.getElementById('container').innerHTML = 'BDT Zero';
return false;
}
var iWordsLength = numReversed.length;
var finalWord = '';
j = 0;
for (i = 0; i < iWordsLength; i++) {
switch (i) {
case 0:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
inWords[j] = inWords[j] + '';
break;
case 1:
tensComplication();
break;
case 2:
if (actnumber[i] == '0') {
inWords[j] = '';
} else if (actnumber[i - 1] !== '0' && actnumber[i - 2] !== '0') {
inWords[j] = iWords[actnumber[i]] + ' hundred';
} else {
inWords[j] = iWords[actnumber[i]] + ' hundred';
}
break;
case 3:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
if (actnumber[i + 1] !== '0' || actnumber[i] > '0') {
inWords[j] = inWords[j] + ' thousand';
}
break;
case 4:
tensComplication();
break;
case 5:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
if (actnumber[i + 1] !== '0' || actnumber[i] > '0') {
inWords[j] = inWords[j] + ' lakh';
}
break;
case 6:
tensComplication();
break;
case 7:
if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
inWords[j] = '';
} else {
inWords[j] = iWords[actnumber[i]];
}
inWords[j] = inWords[j] + ' crore';
break;
case 8:
tensComplication();
break;
default:
break;
}
j++;
}
inWords.reverse();
for (i = 0; i < inWords.length; i++) {
finalWord += inWords[i];
}
return finalWord;
}
</script>
<input type="text" name="bdt" id="bdt" />
<input type="button" name="sr1" value="Click Here" onClick="convertAmount()"/>
<div id="container"></div>
js fiddle
Here taka mean USD and paisa mean cent
This is in response to #LordZardeck's comment to #naomik's excellent answer above. Sorry, I would've commented directly but I've never posted before so I don't have the privilege to do so, so I am posting here instead.
Anyhow, I just happened to translate the ES5 version to a more readable form this past weekend so I'm sharing it here. This should be faithful to the original (including the recent edit) and I hope the naming is clear and accurate.
function int_to_words(int) {
if (int === 0) return 'zero';
var ONES = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
var TENS = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
var SCALE = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];
// Return string of first three digits, padded with zeros if needed
function get_first(str) {
return ('000' + str).substr(-3);
}
// Return string of digits with first three digits chopped off
function get_rest(str) {
return str.substr(0, str.length - 3);
}
// Return string of triplet convereted to words
function triplet_to_words(_3rd, _2nd, _1st) {
return (_3rd == '0' ? '' : ONES[_3rd] + ' hundred ') + (_1st == '0' ? TENS[_2nd] : TENS[_2nd] && TENS[_2nd] + '-' || '') + (ONES[_2nd + _1st] || ONES[_1st]);
}
// Add to words, triplet words with scale word
function add_to_words(words, triplet_words, scale_word) {
return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + words : words;
}
function iter(words, i, first, rest) {
if (first == '000' && rest.length === 0) return words;
return iter(add_to_words(words, triplet_to_words(first[0], first[1], first[2]), SCALE[i]), ++i, get_first(rest), get_rest(rest));
}
return iter('', 0, get_first(String(int)), get_rest(String(int)));
}
var inWords = function(totalRent){
//console.log(totalRent);
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
var number = parseFloat(totalRent).toFixed(2).split(".");
var num = parseInt(number[0]);
var digit = parseInt(number[1]);
//console.log(num);
if ((num.toString()).length > 9) return 'overflow';
var n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
var d = ('00' + digit).substr(-2).match(/^(\d{2})$/);;
if (!n) return; var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'Rupee ' : '';
str += (d[1] != 0) ? ((str != '' ) ? "and " : '') + (a[Number(d[1])] || b[d[1][0]] + ' ' + a[d[1][1]]) + 'Paise ' : 'Only!';
console.log(str);
return str;
}
This is modified code supports for Indian Rupee with 2 decimal place.
Below are the translations from
integer to word
float to word
money to word
Test cases are at the bottom
var ONE_THOUSAND = Math.pow(10, 3);
var ONE_MILLION = Math.pow(10, 6);
var ONE_BILLION = Math.pow(10, 9);
var ONE_TRILLION = Math.pow(10, 12);
var ONE_QUADRILLION = Math.pow(10, 15);
var ONE_QUINTILLION = Math.pow(10, 18);
function integerToWord(integer) {
var prefix = '';
var suffix = '';
if (!integer){ return "zero"; }
if(integer < 0){
prefix = "negative";
suffix = integerToWord(-1 * integer);
return prefix + " " + suffix;
}
if(integer <= 90){
switch (integer) {
case integer < 0:
prefix = "negative";
suffix = integerToWord(-1 * integer);
return prefix + " " + suffix;
case 1: return "one";
case 2: return "two";
case 3: return "three";
case 4: return "four";
case 5: return "five";
case 6: return "six";
case 7: return "seven";
case 8: return "eight";
case 9: return "nine";
case 10: return "ten";
case 11: return "eleven";
case 12: return "twelve";
case 13: return "thirteen";
case 14: return "fourteen";
case 15: return "fifteen";
case 16: return "sixteen";
case 17: return "seventeen";
case 18: return "eighteen";
case 19: return "nineteen";
case 20: return "twenty";
case 30: return "thirty";
case 40: return "forty";
case 50: return "fifty";
case 60: return "sixty";
case 70: return "seventy";
case 80: return "eighty";
case 90: return "ninety";
default: break;
}
}
if(integer < 100){
prefix = integerToWord(integer - integer % 10);
suffix = integerToWord(integer % 10);
return prefix + "-" + suffix;
}
if(integer < ONE_THOUSAND){
prefix = integerToWord(parseInt(Math.floor(integer / 100), 10) ) + " hundred";
if (integer % 100){ suffix = " and " + integerToWord(integer % 100); }
return prefix + suffix;
}
if(integer < ONE_MILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_THOUSAND), 10)) + " thousand";
if (integer % ONE_THOUSAND){ suffix = integerToWord(integer % ONE_THOUSAND); }
}
else if(integer < ONE_BILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_MILLION), 10)) + " million";
if (integer % ONE_MILLION){ suffix = integerToWord(integer % ONE_MILLION); }
}
else if(integer < ONE_TRILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_BILLION), 10)) + " billion";
if (integer % ONE_BILLION){ suffix = integerToWord(integer % ONE_BILLION); }
}
else if(integer < ONE_QUADRILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_TRILLION), 10)) + " trillion";
if (integer % ONE_TRILLION){ suffix = integerToWord(integer % ONE_TRILLION); }
}
else if(integer < ONE_QUINTILLION){
prefix = integerToWord(parseInt(Math.floor(integer / ONE_QUADRILLION), 10)) + " quadrillion";
if (integer % ONE_QUADRILLION){ suffix = integerToWord(integer % ONE_QUADRILLION); }
} else {
return '';
}
return prefix + " " + suffix;
}
function moneyToWord(value){
var decimalValue = (value % 1);
var integer = value - decimalValue;
decimalValue = Math.round(decimalValue * 100);
var decimalText = !decimalValue? '': integerToWord(decimalValue) + ' cent' + (decimalValue === 1? '': 's');
var integerText= !integer? '': integerToWord(integer) + ' dollar' + (integer === 1? '': 's');
return (
integer && !decimalValue? integerText:
integer && decimalValue? integerText + ' and ' + decimalText:
!integer && decimalValue? decimalText:
'zero cents'
);
}
function floatToWord(value){
var decimalValue = (value % 1);
var integer = value - decimalValue;
decimalValue = Math.round(decimalValue * 100);
var decimalText = !decimalValue? '':
decimalValue < 10? "point o' " + integerToWord(decimalValue):
decimalValue % 10 === 0? 'point ' + integerToWord(decimalValue / 10):
'point ' + integerToWord(decimalValue);
return (
integer && !decimalValue? integerToWord(integer):
integer && decimalValue? [integerToWord(integer), decimalText].join(' '):
!integer && decimalValue? decimalText:
integerToWord(0)
);
}
// test
(function(){
console.log('integerToWord ==================================');
for(var i = 0; i < 101; ++i){
console.log('%s=%s', i, integerToWord(i));
}
console.log('floatToWord ====================================');
i = 131;
while(i--){
console.log('%s=%s', i / 100, floatToWord(i / 100));
}
console.log('moneyToWord ====================================');
for(i = 0; i < 131; ++i){
console.log('%s=%s', i / 100, moneyToWord(i / 100));
}
}());
Another conversion that uses remainders and supports different languages:
function numberToWords(number) {
var result = [];
var fraction = number.toFixed(2).split('.');
var integer_part = parseInt(fraction[0]);
// var fractional_part = parseInt(fraction[1]); -- not handled here
var previousNumber = null;
for (var i = 0; i < fraction[0].length; i++) {
var reminder = Math.floor(integer_part % 10);
integer_part /= 10;
var name = getNumberName(reminder, i, fraction[0].length, previousNumber);
previousNumber = reminder;
if (name)
result.push(name);
}
result.reverse();
return result.join(' ');
}
The getNumberName function is language-dependent and handles numbers up to 9999 (but it is easy to extend it to handle larger numbers):
function getNumberName(number, power, places, previousNumber) {
var result = "";
if (power == 1) {
result = handleTeensAndTys(number, previousNumber);
} else if (power == 0 && places != 1 || number == 0) {
// skip number that was handled in teens and zero
} else {
result = locale.numberNames[number.toString()] + locale.powerNames[power.toString()];
}
return result;
}
handleTeensAndTys handles multiples of ten:
function handleTeensAndTys(number, previousNumber) {
var result = "";
if (number == 1) { // teens
if (previousNumber in locale.specialTeenNames) {
result = locale.specialTeenNames[previousNumber];
} else if (previousNumber in locale.specialTyNames) {
result = locale.specialTyNames[previousNumber] + locale.teenSuffix;
} else {
result = locale.numberNames[previousNumber] + locale.teenSuffix;
}
} else if (number == 0) { // previousNumber was not handled in teens
result = locale.numberNames[previousNumber.toString()];
} else { // other tys
if (number in locale.specialTyNames) {
result = locale.specialTyNames[number];
} else {
result = locale.numberNames[number];
}
result += locale.powerNames[1];
if (previousNumber != 0) {
result += " " + locale.numberNames[previousNumber.toString()];
}
}
return result;
}
Finally, locale examples:
var locale = { // English
numberNames: {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine" },
powerNames: {0: "", 1: "ty", 2: " hundred", 3: " thousand" },
specialTeenNames: {0: "ten", 1: "eleven", 2: "twelve" },
specialTyNames: {2: "twen", 3: "thir", 5: "fif" },
teenSuffix: "teen"
};
var locale = { // Estonian
numberNames: {1: "üks", 2: "kaks", 3: "kolm", 4: "neli", 5: "viis", 6: "kuus", 7: "seitse", 8: "kaheksa", 9: "üheksa"},
powerNames: {0: "", 1: "kümmend", 2: "sada", 3: " tuhat" },
specialTeenNames: {0: "kümme"},
specialTyNames: {},
teenSuffix: "teist"
};
Here's a JSFiddle with tests: https://jsfiddle.net/rcrxna7v/15/
Function that will work with decimal values also
function amountToWords(amountInDigits){
// American Numbering System
var th = ['','thousand','million', 'billion','trillion'];
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function toWords(s){
s = s.toString();
s = s.replace(/[\, ]/g,'');
if (s != parseFloat(s))
return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i=0; i < x; i++){
if ((x-i)%3==2){
if (n[i] == '1') {
str += tn[Number(n[i+1])] + ' ';
i++; sk=1;
} else if (n[i]!=0) {
str += tw[n[i]-2] + ' ';sk=1;
}
} else if (n[i]!=0) {
str += dg[n[i]] +' ';
if ((x-i)%3==0)
str += 'hundred ';
sk=1;
} if ((x-i)%3==1) {
if (sk) str += th[(x-i-1)/3] + ' ';sk=0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';
}
return str.replace(/\s+/g,' ');
}
return toWords(amountInDigits);
}
<input type="text" name="number" placeholder="Number OR Amount" onkeyup="word.innerHTML=amountToWords(this.value)" />
<div id="word"></div>
I modified #McShaman's code, converted it to CoffeeScript, and added docs via JSNice. Here's the result, for those interested (English):
###
Convert an integer to an English string equivalent
#param {Integer} number the integer to be converted
#return {String} the English number equivalent
###
inWords = (number) ->
###
#property {Array}
###
englishIntegers = [
""
"one "
"two "
"three "
"four "
"five "
"six "
"seven "
"eight "
"nine "
"ten "
"eleven "
"twelve "
"thirteen "
"fourteen "
"fifteen "
"sixteen "
"seventeen "
"eighteen "
"nineteen "
]
###
#property {Array}
###
englishIntegerTens = [
""
""
"twenty"
"thirty"
"forty"
"fifty"
"sixty"
"seventy"
"eighty"
"ninety"
]
###
#property {Array}
###
englishIntegerThousands = [
"thousand"
"million"
""
]
number = number.toString()
return "" if number.length > 9
###
#property {string}
###
number = ("000000000" + number).substr(-9)
###
#property {(Array.<string>|null)}
###
number = number.match(/.{3}/g)
###
#property {string}
###
convertedWords = ""
###
#property {number}
###
i = 0
while i < englishIntegerThousands.length
###
#property {string}
###
currentNumber = number[i]
###
#property {string}
###
tempResult = ""
tempResult += (if convertedWords isnt "" then " " + englishIntegerThousands[i] + " " else "")
tempResult += (if currentNumber[0] isnt 0 then englishIntegers[Number(currentNumber[0])] + "hundred " else "")
###
#property {string}
###
currentNumber = currentNumber.substr(1)
tempResult += (if currentNumber isnt 0 then ((if tempResult isnt "" then "and " else "")) + (englishIntegers[Number(currentNumber)] or englishIntegerTens[currentNumber[0]] + " " + englishIntegers[currentNumber[1]]) else "")
convertedWords += tempResult
i++
convertedWords
Though, this question has been answered - still I want to share something I recently developed in java script (based on the logic of an old C#. Net implementation I found in Internet) for converting Indian currency values to Words. It can handle up to 40 digits. You can have a look.
Usage:
InrToWordConverter.Initialize();.
var inWords = InrToWordConverter.ConvertToWord(amount);
Implementation:
htPunctuation = {};
listStaticSuffix = {};
listStaticPrefix = {};
listHelpNotation = {};
var InrToWordConverter = function () {
};
InrToWordConverter.Initialize = function () {
InrToWordConverter.LoadStaticPrefix();
InrToWordConverter.LoadStaticSuffix();
InrToWordConverter.LoadHelpofNotation();
};
InrToWordConverter.ConvertToWord = function (value) {
value = value.toString();
if (value) {
var tokens = value.split(".");
var rsPart = "";
var psPart = "";
if (tokens.length === 2) {
rsPart = String.trim(tokens[0]) || "0";
psPart = String.trim(tokens[1]) || "0";
}
else if (tokens.length === 1) {
rsPart = String.trim(tokens[0]) || "0";
psPart = "0";
}
else {
rsPart = "0";
psPart = "0";
}
htPunctuation = {};
var rsInWords = InrToWordConverter.ConvertToWordInternal(rsPart) || "Zero";
var psInWords = InrToWordConverter.ConvertToWordInternal(psPart) || "Zero";
var result = "Rupees " + rsInWords + "and " + psInWords + " Paise.";
return result;
}
};
InrToWordConverter.ConvertToWordInternal = function (value) {
var convertedString = "";
if (!(value.toString().length > 40))
{
if (InrToWordConverter.IsNumeric(value.toString()))
{
try
{
var strValue = InrToWordConverter.Reverse(value);
switch (strValue.length)
{
case 1:
if (parseInt(strValue.toString()) > 0) {
convertedString = InrToWordConverter.GetWordConversion(value);
}
else {
convertedString = "Zero ";
}
break;
case 2:
convertedString = InrToWordConverter.GetWordConversion(value);
break;
default:
InrToWordConverter.InsertToPunctuationTable(strValue);
InrToWordConverter.ReverseHashTable();
convertedString = InrToWordConverter.ReturnHashtableValue();
break;
}
}
catch (exception) {
convertedString = "Unexpected Error Occured <br/>";
}
}
else {
convertedString = "Please Enter Numbers Only, Decimal Values Are not supported";
}
}
else {
convertedString = "Please Enter Value in Less Then or Equal to 40 Digit";
}
return convertedString;
};
InrToWordConverter.IsNumeric = function (valueInNumeric) {
var isFine = true;
valueInNumeric = valueInNumeric || "";
var len = valueInNumeric.length;
for (var i = 0; i < len; i++) {
var ch = valueInNumeric[i];
if (!(ch >= '0' && ch <= '9')) {
isFine = false;
break;
}
}
return isFine;
};
InrToWordConverter.ReturnHashtableValue = function () {
var strFinalString = "";
var keysArr = [];
for (var key in htPunctuation) {
keysArr.push(key);
}
for (var i = keysArr.length - 1; i >= 0; i--) {
var hKey = keysArr[i];
if (InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) !== "") {
strFinalString = strFinalString + InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) + InrToWordConverter.StaticPrefixFind((hKey).toString());
}
}
return strFinalString;
};
InrToWordConverter.ReverseHashTable = function () {
var htTemp = {};
for (var key in htPunctuation) {
var item = htPunctuation[key];
htTemp[key] = InrToWordConverter.Reverse(item.toString());
}
htPunctuation = {};
htPunctuation = htTemp;
};
InrToWordConverter.InsertToPunctuationTable = function (strValue) {
htPunctuation[1] = strValue.substr(0, 3).toString();
var j = 2;
for (var i = 3; i < strValue.length; i = i + 2) {
if (strValue.substr(i).length > 0) {
if (strValue.substr(i).length >= 2) {
htPunctuation[j] = strValue.substr(i, 2).toString();
}
else {
htPunctuation[j] = strValue.substr(i, 1).toString();
}
}
else {
break;
}
j++;
}
};
InrToWordConverter.Reverse = function (strValue) {
var reversed = "";
for (var i in strValue) {
var ch = strValue[i];
reversed = ch + reversed;
}
return reversed;
};
InrToWordConverter.GetWordConversion = function (inputNumber) {
var toReturnWord = "";
if (inputNumber.length <= 3 && inputNumber.length > 0) {
if (inputNumber.length === 3) {
if (parseInt(inputNumber.substr(0, 1)) > 0) {
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1)) + "Hundred ";
}
var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 2));
if (tempString === "")
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1) + "0");
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(2, 1));
}
toReturnWord = toReturnWord + tempString;
}
if (inputNumber.length === 2)
{
var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 2));
if (tempString === "")
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1) + "0");
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1));
}
toReturnWord = toReturnWord + tempString;
}
if (inputNumber.length === 1)
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1));
}
}
return toReturnWord;
};
InrToWordConverter.StaticSuffixFind = function (numberKey) {
var valueFromNumber = "";
for (var key in listStaticSuffix) {
if (String.trim(key.toString()) === String.trim(numberKey)) {
valueFromNumber = listStaticSuffix[key].toString();
break;
}
}
return valueFromNumber;
};
InrToWordConverter.StaticPrefixFind = function (numberKey) {
var valueFromNumber = "";
for (var key in listStaticPrefix) {
if (String.trim(key) === String.trim(numberKey)) {
valueFromNumber = listStaticPrefix[key].toString();
break;
}
}
return valueFromNumber;
};
InrToWordConverter.StaticHelpNotationFind = function (numberKey) {
var helpText = "";
for (var key in listHelpNotation) {
if (String.trim(key.toString()) === String.trim(numberKey)) {
helpText = listHelpNotation[key].toString();
break;
}
}
return helpText;
};
InrToWordConverter.LoadStaticPrefix = function () {
listStaticPrefix[2] = "Thousand ";
listStaticPrefix[3] = "Lac ";
listStaticPrefix[4] = "Crore ";
listStaticPrefix[5] = "Arab ";
listStaticPrefix[6] = "Kharab ";
listStaticPrefix[7] = "Neel ";
listStaticPrefix[8] = "Padma ";
listStaticPrefix[9] = "Shankh ";
listStaticPrefix[10] = "Maha-shankh ";
listStaticPrefix[11] = "Ank ";
listStaticPrefix[12] = "Jald ";
listStaticPrefix[13] = "Madh ";
listStaticPrefix[14] = "Paraardha ";
listStaticPrefix[15] = "Ant ";
listStaticPrefix[16] = "Maha-ant ";
listStaticPrefix[17] = "Shisht ";
listStaticPrefix[18] = "Singhar ";
listStaticPrefix[19] = "Maha-singhar ";
listStaticPrefix[20] = "Adant-singhar ";
};
InrToWordConverter.LoadStaticSuffix = function () {
listStaticSuffix[1] = "One ";
listStaticSuffix[2] = "Two ";
listStaticSuffix[3] = "Three ";
listStaticSuffix[4] = "Four ";
listStaticSuffix[5] = "Five ";
listStaticSuffix[6] = "Six ";
listStaticSuffix[7] = "Seven ";
listStaticSuffix[8] = "Eight ";
listStaticSuffix[9] = "Nine ";
listStaticSuffix[10] = "Ten ";
listStaticSuffix[11] = "Eleven ";
listStaticSuffix[12] = "Twelve ";
listStaticSuffix[13] = "Thirteen ";
listStaticSuffix[14] = "Fourteen ";
listStaticSuffix[15] = "Fifteen ";
listStaticSuffix[16] = "Sixteen ";
listStaticSuffix[17] = "Seventeen ";
listStaticSuffix[18] = "Eighteen ";
listStaticSuffix[19] = "Nineteen ";
listStaticSuffix[20] = "Twenty ";
listStaticSuffix[30] = "Thirty ";
listStaticSuffix[40] = "Fourty ";
listStaticSuffix[50] = "Fifty ";
listStaticSuffix[60] = "Sixty ";
listStaticSuffix[70] = "Seventy ";
listStaticSuffix[80] = "Eighty ";
listStaticSuffix[90] = "Ninty ";
};
InrToWordConverter.LoadHelpofNotation = function () {
listHelpNotation[2] = "=1,000 (3 Trailing Zeros)";
listHelpNotation[3] = "=1,00,000 (5 Trailing Zeros)";
listHelpNotation[4] = "=1,00,00,000 (7 Trailing Zeros)";
listHelpNotation[5] = "=1,00,00,00,000 (9 Trailing Zeros)";
listHelpNotation[6] = "=1,00,00,00,00,000 (11 Trailing Zeros)";
listHelpNotation[7] = "=1,00,00,00,00,00,000 (13 Trailing Zeros)";
listHelpNotation[8] = "=1,00,00,00,00,00,00,000 (15 Trailing Zeros)";
listHelpNotation[9] = "=1,00,00,00,00,00,00,00,000 (17 Trailing Zeros)";
listHelpNotation[10] = "=1,00,00,00,00,00,00,00,00,000 (19 Trailing Zeros)";
listHelpNotation[11] = "=1,00,00,00,00,00,00,00,00,00,000 (21 Trailing Zeros)";
listHelpNotation[12] = "=1,00,00,00,00,00,00,00,00,00,00,000 (23 Trailing Zeros)";
listHelpNotation[13] = "=1,00,00,00,00,00,00,00,00,00,00,00,000 (25 Trailing Zeros)";
listHelpNotation[14] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,000 (27 Trailing Zeros)";
listHelpNotation[15] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (29 Trailing Zeros)";
listHelpNotation[16] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (31 Trailing Zeros)";
listHelpNotation[17] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (33 Trailing Zeros)";
listHelpNotation[18] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (35 Trailing Zeros)";
listHelpNotation[19] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (37 Trailing Zeros)";
listHelpNotation[20] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (39 Trailing Zeros)";
};
if (!String.trim) {
String.trim = function (str) {
var result = "";
var firstNonWhiteSpaceFound = false;
var startIndex = -1;
var endIndex = -1;
if (str) {
for (var i = 0; i < str.length; i++) {
if (firstNonWhiteSpaceFound === false) {
if (str[i] === ' ' || str[i] === '\t') {
continue;
}
else {
firstNonWhiteSpaceFound = true;
startIndex = i;
endIndex = i;
}
}
else {
if (str[i] === ' ' || str[i] === '\t') {
continue;
}
else {
endIndex = i;
}
}
}
if (startIndex !== -1 && endIndex !== -1) {
result = str.slice(startIndex, endIndex + 1);
}
}
return result;
};
}
Try this code with a Turkish currency compliant JavaScript
function dene() {
var inpt = document.getElementById("tar1").value;
var spt = inpt.split('');
spt.reverse();
var tek = ["", "Bir", "İki", "Üç", "Dört", "Beş", "Altı", "Yedi", "Sekiz", "Dokuz"];
var onlu = ["", "On", "Yirmi", "Otuz", "Kırk", "Elli", "Atmış", "Yetmiş", "Seksen", "Doksan"];
var Yuz = ["", "Yüz", "İkiYüz", "Üçyüz", "DörtYüz", "BeşYüz", "AltıYüz", "YediYüz", "SekizYüz", "DokuzYüz"];
var ska = ["", "", "", "", "Bin", "Milyon", "Milyar", "Trilyon", "Katrilyon", "Kentilyon"];
var i, j;
var bas3 = "";
var bas6 = "";
var bas9 = "";
var bas12 = "";
var total;
for(i = 0; i < 1; i++) {
bas3 += Yuz[spt[i+2]] + onlu[spt[i+1]] + tek[spt[i]];
bas6 += Yuz[spt[i+5]] + onlu[spt[i+4]] + tek[spt[i+3]] + ska[4];
bas9 += Yuz[spt[i+8]] + onlu[spt[i+7]] + tek[spt[i+6]] + ska[5];
bas12 += Yuz[spt[i+11]] + onlu[spt[i+10]] + tek[spt[i+9]] + ska[6];
if(inpt.length < 4) {
bas6 = '';
bas9 = '';
}
if(inpt.length > 6 && inpt.slice(5, 6) == 0) {
bas6 = bas6.replace(/Bin/g, '');
}
if(inpt.length < 7) {
bas9 = '';
}
if(inpt.length > 9 && inpt.slice(1,3) == 000){
bas9 = bas9.replace(/Milyon/g, '');
}
if(inpt.length < 10) {
bas12 = '';
}
}
total = bas12 + bas9 + bas6 + bas3;
total = total.replace(NaN, '');
total = total.replace(undefined, '');
document.getElementById('demo').innerHTML =
total;
}
Lot of good answers. I needed mine for Indian (South Asian) numbering system. I modified one of the codes above - attaching it here, in case, someone else needs this. In the Indian numbering system, groups after thousands are in in 2 digits, not 3 as in the western system.
var IS_SOUTH_ASIAN = true;
function int_to_words(int) {
if (int === 0) return 'zero';
var ONES_WORD = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
var TENS_WORD = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
var SCALE_WORD_WESTERN = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];
var SCALE_WORD_SOUTH_ASIAN = ['','thousand','lakh','crore','arab','kharab','neel','padma','shankh','***','***'];
var GROUP_SIZE = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? 2 : 3;
var SCALE_WORD = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? SCALE_WORD_SOUTH_ASIAN : SCALE_WORD_WESTERN;
// Return string of first three digits, padded with zeros if needed
function get_first_3(str) {
return ('000' + str).substr(-(3));
}
function get_first(str) { //-- Return string of first GROUP_SIZE digits, padded with zeros if needed, if group size is 2, make it size 3 by prefixing with a '0'
return (GROUP_SIZE == 2 ? '0' : '') + ('000' + str).substr(-(GROUP_SIZE));
}
// Return string of digits with first three digits chopped off
function get_rest_3(str) {
return str.substr(0, str.length - 3);
}
function get_rest(str) { // Return string of digits with first GROUP_SIZE digits chopped off
return str.substr(0, str.length - GROUP_SIZE);
}
// Return string of triplet convereted to words
function triplet_to_words(_3rd, _2nd, _1st) {
return (_3rd == '0' ? '' : ONES_WORD[_3rd] + ' hundred ') +
(_1st == '0' ? TENS_WORD[_2nd] : TENS_WORD[_2nd] && TENS_WORD[_2nd] + '-' || '') +
(ONES_WORD[_2nd + _1st] || ONES_WORD[_1st]); //-- 1st one returns one-nineteen - second one returns one-nine
}
// Add to result, triplet words with scale word
function add_to_result(result, triplet_words, scale_word) {
return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + result : result;
}
function recurse (result, scaleIdx, first, rest) {
if (first == '000' && rest.length === 0) return result;
var newResult = add_to_result (result, triplet_to_words (first[0], first[1], first[2]), SCALE_WORD[scaleIdx]);
return recurse (newResult, ++scaleIdx, get_first(rest), get_rest(rest));
}
return recurse ('', 0, get_first_3(String(int)), get_rest_3(String(int)));
}
while this system does use a for loop, It uses US english and is fast, accurate, and expandable(you can add infinite values to the "th" var and they will be included).
This function grabs the 3 groups of numbers backwards so it can get the number groups where a , would normally separate them in the numeric form. Then each group of three numbers is added to an array with the word form of just the 3 numbers(ex: one hundred twenty three). It then takes that new array list, and reverses it again, while adding the th var of the same index to the end of the string.
var ones = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var tens = ['', '', 'twenty ','thirty ','forty ','fifty ', 'sixty ','seventy ','eighty ','ninety ', 'hundred '];
var th = ['', 'thousand ','million ','billion ', 'trillion '];
function numberToWord(number){
var text = "";
var size = number.length;
var textList = [];
var textListCount = 0;
//get each 3 digit numbers
for(var i = number.length-1; i >= 0; i -= 3){
//get 3 digit group
var num = 0;
if(number[(i-2)]){num += number[(i-2)];}
if(number[(i-1)]){num += number[(i-1)];}
if(number[i]){num += number[i];}
//remove any extra 0's from begining of number
num = Math.floor(num).toString();
if(num.length == 1 || num < 20){
//if one digit or less than 20
textList[textListCount] = ones[num];
}else if(num.length == 2){
//if 2 digits and greater than 20
textList[textListCount] = tens[num[0]]+ones[num[1]];
}else if(num.length == 3){
//if 3 digits
textList[textListCount] = ones[num[0]]+tens[10]+tens[num[1]]+ones[num[2]];
}
textListCount++;
}
//add the list of 3 digit groups to the string
for(var i = textList.length-1; i >= 0; i--){
if(textList[i] !== ''){text += textList[i]+th[i];} //skip if the number was 0
}
return text;
}
This is also in response to naomik's excellent post! Unfortunately I don't have the rep to post in the correct place but I leave this here in case it can help anyone.
If you need British English written form you need to make some adaptions to the code. British English differs from the American in a couple of ways. Basically you need to insert the word 'and' in two specific places.
After a hundred assuming there are tens and ones. E.g One hundred and ten. One thousand and seventeen. NOT One thousand one hundred and.
In certain edges, after a thousand, a million, a billion etc. when there are no smaller units. E.g. One thousand and ten. One million and forty four. NOT One million and one thousand.
The first situation can be addressed by checking for 10s and 1s in the makeGroup method and appending 'and' when they exist.
makeGroup = ([ones,tens,huns]) => {
var adjective = this.num(ones) ? ' hundred and ' : this.num(tens) ? ' hundred and ' : ' hundred';
return [
this.num(huns) === 0 ? '' : this.a[huns] + adjective,
this.num(ones) === 0 ? this.b[tens] : this.b[tens] && this.b[tens] + '-' || '',
this.a[tens+ones] || this.a[ones]
].join('');
};
The second case is more complicated. It is equivalent to
add 'and' to 'a million, a thousand', or 'a billion' if the antepenultimate number is zero. e.g.
1,100,057 one million one hundred thousand and fifty seven.
5,000,006 five million and six
I think this could be implemented in #naomik's code through the use of a filter function but I wasn't able to work out how. In the end I settled on hackily looping through the returned array of words and using indexOf to look for instances where the word 'hundred' was missing from the final element.
I've just written paisa.js to do this, and it handles lakhs and crores correctly as well, can check it out. The core looks a bit like this:
const regulars = [
{
1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'
},
{
2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'
}
]
const exceptions = {
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen'
}
const partInWords = (part) => {
if (parseInt(part) === 0) return
const digits = part.split('')
const words = []
if (digits.length === 3) {
words.push([regulars[0][digits.shift()], 'hundred'].join(' '))
}
if (exceptions[digits.join('')]) {
words.push(exceptions[digits.join('')])
} else {
words.push(digits.reverse().reduce((memo, el, i) => {
memo.unshift(regulars[i][el])
return memo
}, []).filter(w => w).join(' '))
}
return words.filter(w => w.trim().length).join(' and ')
}
My solution is based on Juan Gaitán's solution for Indian currency, works up to crores.
function valueInWords(value) {
let ones = ['', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
let tens = ['twenty','thirty', 'forty','fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
let digit = 0;
if (value < 20) return ones[value];
if (value < 100) {
digit = value % 10; //remainder
return tens[Math.floor(value/10)-2] + " " + (digit > 0 ? ones[digit] : "");
}
if (value < 1000) {
return ones[Math.floor(value/100)] + " hundred " + (value % 100 > 0 ? valueInWords(value % 100) : "");
}
if (value < 100000) {
return valueInWords(Math.floor(value/1000)) + " thousand " + (value % 1000 > 0 ? valueInWords(value % 1000) : "");
}
if (value < 10000000) {
return valueInWords(Math.floor(value/100000)) + " lakh " + (value % 100000 > 0 ? valueInWords(value % 100000) : "");
}
return valueInWords(Math.floor(value/10000000)) + " crore " + (value % 10000000 > 0 ? valueInWords(value % 10000000) : "");
}
function numberToEnglish( n ) {
var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g,"");
/* Is number zero? */
if( parseInt( string ) === 0 ) {
return 'zero';
}
/* Array of units as words */
units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
/* Array of tens as words */
tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
/* Array of scales as words */
scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
/* Split user argument into 3 digit chunks from right to left */
start = string.length;
chunks = [];
while( start > 0 ) {
end = start;
chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
}
/* Check if function has enough scale words to be able to stringify the user argument */
chunksLen = chunks.length;
if( chunksLen > scales.length ) {
return '';
}
/* Stringify each integer in each chunk */
words = [];
for( i = 0; i < chunksLen; i++ ) {
chunk = parseInt( chunks[i] );
if( chunk ) {
/* Split chunk into array of individual integers */
ints = chunks[i].split( '' ).reverse().map( parseFloat );
/* If tens integer is 1, i.e. 10, then add 10 to units integer */
if( ints[1] === 1 ) {
ints[0] += 10;
}
/* Add scale word if chunk is not zero and array item exists */
if( ( word = scales[i] ) ) {
words.push( word );
}
/* Add unit word if array item exists */
if( ( word = units[ ints[0] ] ) ) {
words.push( word );
}
/* Add tens word if array item exists */
if( ( word = tens[ ints[1] ] ) ) {
words.push( word );
}
/* Add 'and' string after units or tens integer if: */
if( ints[0] || ints[1] ) {
/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
if( ints[2] || ! i && chunksLen ) {
words.push( and );
}
}
/* Add hundreds word if array item exists */
if( ( word = units[ ints[2] ] ) ) {
words.push( word + ' hundred' );
}
}
}
return words.reverse().join( ' ' );
}
// - - - - - Tests - - - - - -
function test(v) {
var sep = ('string'==typeof v)?'"':'';
console.log("numberToEnglish("+sep + v.toString() + sep+") = "+numberToEnglish(v));
}
test(2);
test(721);
test(13463);
test(1000001);
test("21,683,200,000,621,384");
For those who are looking for imperial/english naming conventions.
Based on #Salman's answer
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function inWords (num) {
if ((num = num.toString()).length > 12) return 'overflow';
n = ('00000000000' + num).substr(-12).match(/^(\d{3})(\d{3})(\d{3})(\d{1})(\d{2})$/);
if (!n) return; var str = '';
str += (n[1] != 0) ? (Number(n[1]) > 99 ? this.a[Number(n[1][0])] + 'hundred ' : '') + (a[Number(n[1])] || b[n[1][1]] + ' ' + a[n[1][2]]) + 'billion ' : '';
str += (n[2] != 0) ? (Number(n[2]) > 99 ? this.a[Number(n[2][0])] + 'hundred ' : '') + (a[Number(n[2])] || b[n[2][1]] + ' ' + a[n[2][2]]) + 'million ' : '';
str += (n[3] != 0) ? (Number(n[3]) > 99 ? this.a[Number(n[3][0])] + 'hundred ' : '') + (a[Number(n[3])] || b[n[3][1]] + ' ' + a[n[3][2]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (Number(n[5]) !== 0) ? ((str !== '') ? 'and ' : '') +
(this.a[Number(n[5])] || this.b[n[5][0]] + ' ' +
this.a[n[5][1]]) + '' : '';
return str;
}
document.getElementById('number').onkeyup = function () {
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
<span id="words"></span>
<input id="number" type="text" />
Cleanest and easiest approach that came to mind:
const numberText = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand',
}
const numberValues = Object.keys(numberText)
.map((val) => Number(val))
.sort((a, b) => b - a)
const convertNumberToEnglishText = (n) => {
if (n === 0) return 'zero'
if (n < 0) return 'negative ' + convertNumberToEnglishText(-n)
let num = n
let text = ''
for (const numberValue of numberValues) {
const count = Math.trunc(num / numberValue)
if (count < 1) continue
if (numberValue >= 100) text += convertNumberToEnglishText(count) + ' '
text += numberText[numberValue] + ' '
num -= count * numberValue
}
if (num !== 0) throw Error('Something went wrong!')
return text.trim()
}
Probably the simplest one I got and used was from Ben E. I made modifications to his code since it would only return for example 'Five Hundred' when you try to convert 500,000.00. I just added a line of conditional code to fix it. Also added the provision for giving out the last two decimal places. I'm now using it to convert the amount to words when printing checks. Here was my revision added to it:
if (Math.floor((number%(100*Math.pow(1000,i))/Math.pow(1000,i))) == 0) {
word = first[Math.floor(tempNumber/(100*Math.pow(1000,i)))] + 'Hundred ' + mad[i]
+ ' ' + word;
} else {
I'm having a hard time pasting the code here but let me know if you need any clarifications
answared by #pramod kharade
simplified
function NumToWord(inputNumber) {
var str = new String(inputNumber)
var splt = str.split("");
var rev = splt.reverse();
var once = ['Zero', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'];
var twos = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
var tens = ['', 'Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];
numLength = rev.length;
var word = new Array();
var j = 0;
for (i = 0; i < numLength; i++) {
switch (i) {
case 0:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = '' + once[rev[i]];
}
word[j] = word[j];
break;
case 1:
aboveTens();
break;
case 2:
if (rev[i] == 0) {
word[j] = '';
}
else if ((rev[i - 1] == 0) || (rev[i - 2] == 0)) {
word[j] = once[rev[i]] + " Hundred ";
}
else {
word[j] = once[rev[i]] + " Hundred and";
}
break;
case 3:
if (rev[i] == 0 || rev[i + 1] == 1) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if ((rev[i + 1] != 0) || (rev[i] > 0)) {
word[j] = word[j] + " Thousand";
}
break;
case 4:
aboveTens();
break;
case 5:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if (rev[i + 1] !== '0' || rev[i] > '0') {
word[j] = word[j] + " Lakh";
}
break;
case 6:
aboveTens();
break;
case 7:
if ((rev[i] == 0) || (rev[i + 1] == 1)) {
word[j] = '';
}
else {
word[j] = once[rev[i]];
}
if (rev[i + 1] !== '0' || rev[i] > '0') {
word[j] = word[j] + " Crore";
}
break;
case 8:
aboveTens();
break;
default: break;
}
j++;
}
function aboveTens() {
if (rev[i] == 0) { word[j] = ''; }
else if (rev[i] == 1) { word[j] = twos[rev[i - 1]]; }
else { word[j] = tens[rev[i]]; }
}
word.reverse();
var finalOutput = '';
for (i = 0; i < numLength; i++) {
finalOutput = finalOutput + word[i];
}
return finalOutput;
}
console.log(NumToWord(123))
console.log(NumToWord(12345678))
console.log(NumToWord(12334543))
console.log(NumToWord(6789876123))
Convertirlos en Español
class Converter {
constructor() {
this.unit = ['CERO', 'UN', 'DOS', 'TRES', 'CUATRO', 'CINCO', 'SEIS', 'SIETE', 'OCHO', 'NUEVE'];
this.units = ['CERO', 'UNO', 'DOS', 'TRES', 'CUATRO', 'CINCO', 'SEIS', 'SIETE', 'OCHO', 'NUEVE'];
this.tenToSixteen = ['DIEZ', 'ONCE', 'DOCE', 'TRECE', 'CATORCE', 'QUINCE', 'DIECISEIS'];
this.tens = ['TREINTA', 'CUARENTA', 'CINCUENTA', 'SESENTA', 'SETENTA', 'OCHENTA', 'NOVENTA'];
this.monedaSingular = " PESO";
this.monedaPlural = " PESOS";
this.monedaMillon = " DE PESOS";
this.centavoSingular = " CENTAVO"
this.centavoPlural = " CENTAVOS"
this.elMessage = document.getElementById('message');
this.addListener();
}
addListener() {
let elInput = document.getElementById('field-number');
elInput.addEventListener('keyup', () => {
if (elInput.value !== '') {
this.convertToText(elInput.value);
} else {
this.elMessage.innerText = '';
}
});
}
convertToText(number) {
number = this.deleteZerosLeft(number);
if (!this.validateNumber(number)) {
this.elMessage.innerText = 'Sólo se aceptan números enteros positivos.';
return;
}
let num = number;
number = number.split(".")[0];
let entero = this.getName(number);
let moneda;
if (parseInt(number) == 1) {
//this.elMessage.innerText =
moneda = entero + this.monedaSingular;
} else {
moneda = entero + this.monedaPlural;
}
if (num.indexOf('.') >= 0) {
let d = num.split(".")[1];
d = this.getName(d);
if (parseInt(d) == 0) {
moneda = moneda;
} else if (parseInt(d) == 1) {
moneda = moneda + " CON " + d + " " + this.centavoSingular;
} else {
moneda = moneda + " CON " + d + " " + this.centavoPlural;
}
}
this.elMessage.innerText = moneda;
}
// Elimina los ceros a la izquierda
deleteZerosLeft(number) {
let i = 0;
let isZero = true;
for (i = 0; i < number.length; i++) {
if (number.charAt(i) != 0) {
isZero = false;
break;
}
}
return isZero ? '0' : number.substr(i);
}
validateNumber(number) {
// Validar que la cadena sea un número y que no esté vacía
if (isNaN(number) || number === '') {
return false;
}
// Validar que el número no sea negativo
if (number.indexOf('-') >= 0) {
return false;
}
return true;
}
getName(number) {
number = this.deleteZerosLeft(number);
if (number.length === 1) {
return this.getUnits(number);
}
if (number.length === 2) {
return this.getTens(number);
}
if (number.length === 3) {
return this.getHundreds(number);
}
if (number.length < 7) {
return this.getThousands(number);
}
if (number.length < 13) {
return this.getPeriod(number, 6, 'MILLON');
}
if (number.length < 19) {
return this.getPeriod(number, 12, 'BILLON');
}
return 'Número demasiado grande.';
}
getUnits(number) {
let numberInt = parseInt(number);
return this.unit[numberInt];
}
getTens(number) {
// Obtener las unidades
let units = number.charAt(1);
if (number < 17) {
return this.tenToSixteen[number - 10];
}
if (number < 20) {
return 'DIECI' + this.getUnits(units);
}
// Nombres especiales
switch (number) {
case '20':
return 'VEINTE';
case '22':
return 'VEINTIDOS';
case '23':
return 'VEINTITRES';
case '26':
return 'VEINTISEIS';
}
if (number < 30) {
return 'VEINTI' + this.getUnits(units);
}
let name = this.tens[number.charAt(0) - 3];
if (units > 0) {
name += ' Y ' + this.getUnits(units);
}
return name;
}
getHundreds(number) {
let name = '';
// Obtener las centenas
let hundreds = number.charAt(0);
// Obtener las decenas y unidades
let tens = number.substr(1);
if (number == 100) {
return 'CIEN';
}
// Nombres especiales
switch(hundreds) {
case '1':
name = 'CIENTO';
break;
case '5':
name = 'QUINIENTOS';
break;
case '7':
name = 'SETECIENTOS';
break;
case '9':
name = 'NOVECIENTOS';
}
if (name === '') {
name = this.getUnits(hundreds) + 'CIENTOS';
}
if (tens > 0) {
name += ' ' + this.getName(tens);
}
return name;
}
getThousands(number) {
let name = 'MIL';
// Obtener cuantos dígitos están en los miles
let thousandsLength = number.length - 3;
// Obtener los miles
let thousands = number.substr(0, thousandsLength);
// Obtener las centenas, decenas y unidades
let hundreds = number.substr(thousandsLength);
if (thousands > 1) {
// Se reemplaza la palabra uno por un en numeros como 21000, 31000, 41000, etc.
name = this.getName(thousands).replace('UNO', 'UN') + ' MIL';
}
if (hundreds > 0) {
name += ' ' + this.getName(hundreds);
}
return name;
}
// Obtiene periodos, por ejemplo: millones, billones, etc.
getPeriod(number, digitsToTheRight, periodName) {
let name = 'UN ' + periodName;
// Obtener cuantos dígitos están dentro del periodo
let periodLength = number.length - digitsToTheRight;
// Obtener los dítos del periodo
let periodDigits = number.substr(0, periodLength);
// Obtener los digitos previos al periodo
let previousDigits = number.substr(periodLength);
if (periodDigits > 1) {
name = this.getName(periodDigits).replace('UNO', 'UN') + ' ' + periodName.replace('Ó', 'O') + 'ES';
}
if (previousDigits > 0) {
name += ' ' + this.getName(previousDigits);
}
return name;
}
}
new Converter();

Transform number in string to alphabetics number [duplicate]

I'm trying to convert numbers into english words, for example 1234 would become: "one thousand two hundred thirty four".
My Tactic goes like this:
Separate the digits to three and put them on Array (finlOutPut), from right to left.
Convert each group (each cell in the finlOutPut array) of three digits to a word (this what the triConvert function does). If all the three digits are zero convert them to "dontAddBigSuffix"
From Right to left, add thousand, million, billion, etc. If the finlOutPut cell equals "dontAddBigSufix" (because it was only zeroes), don't add the word and set the cell to " " (nothing).
It seems to work pretty well, but I've got some problems with numbers like 190000009, converted to: "one hundred ninety million". Somehow it "forgets" the last numbers when there are a few zeros.
What did I do wrong? Where is the bug? Why does it not work perfectly?
function update(){
var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');
var output = '';
var numString = document.getElementById('number').value;
var finlOutPut = new Array();
if (numString == '0') {
document.getElementById('container').innerHTML = 'Zero';
return;
}
if (numString == 0) {
document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
return;
}
var i = numString.length;
i = i - 1;
//cut the number to grups of three digits and add them to the Arry
while (numString.length > 3) {
var triDig = new Array(3);
triDig[2] = numString.charAt(numString.length - 1);
triDig[1] = numString.charAt(numString.length - 2);
triDig[0] = numString.charAt(numString.length - 3);
var varToAdd = triDig[0] + triDig[1] + triDig[2];
finlOutPut.push(varToAdd);
i--;
numString = numString.substring(0, numString.length - 3);
}
finlOutPut.push(numString);
finlOutPut.reverse();
//conver each grup of three digits to english word
//if all digits are zero the triConvert
//function return the string "dontAddBigSufix"
for (j = 0; j < finlOutPut.length; j++) {
finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
}
var bigScalCntr = 0; //this int mark the million billion trillion... Arry
for (b = finlOutPut.length - 1; b >= 0; b--) {
if (finlOutPut[b] != "dontAddBigSufix") {
finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
bigScalCntr++;
}
else {
//replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
finlOutPut[b] = ' ';
bigScalCntr++; //advance the counter
}
}
//convert The output Arry to , more printable string
for(n = 0; n<finlOutPut.length; n++){
output +=finlOutPut[n];
}
document.getElementById('container').innerHTML = output;//print the output
}
//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
var hundred = ' hundred';
var output = '';
var numString = num.toString();
if (num == 0) {
return 'dontAddBigSufix';
}
//the case of 10, 11, 12 ,13, .... 19
if (num < 20) {
output = ones[num];
return output;
}
//100 and more
if (numString.length == 3) {
output = ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output += ones[parseInt(numString.charAt(2))];
return output;
}
output += tens[parseInt(numString.charAt(0))];
output += ones[parseInt(numString.charAt(1))];
return output;
}
<input type="text"
id="number"
size="70"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"/>
<br/>
<div id="container">Here The Numbers Printed</div>
JavaScript is parsing the group of 3 numbers as an octal number when there's a leading zero digit. When the group of three digits is all zeros, the result is the same whether the base is octal or decimal.
But when you give JavaScript '009' (or '008'), that's an invalid octal number, so you get zero back.
If you had gone through the whole set of numbers from 190,000,001 to 190,000,010 you'd hav seen JavaScript skip '...,008' and '...,009' but emit 'eight' for '...,010'. That's the 'Eureka!' moment.
Change:
for (j = 0; j < finlOutPut.length; j++) {
finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
}
to
for (j = 0; j < finlOutPut.length; j++) {
finlOutPut[j] = triConvert(parseInt(finlOutPut[j],10));
}
Code also kept on adding commas after every non-zero group, so I played with it and found the right spot to add the comma.
Old:
for (b = finlOutPut.length - 1; b >= 0; b--) {
if (finlOutPut[b] != "dontAddBigSufix") {
finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
bigScalCntr++;
}
else {
//replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
finlOutPut[b] = ' ';
bigScalCntr++; //advance the counter
}
}
//convert The output Arry to , more printable string
for(n = 0; n<finlOutPut.length; n++){
output +=finlOutPut[n];
}
New:
for (b = finlOutPut.length - 1; b >= 0; b--) {
if (finlOutPut[b] != "dontAddBigSufix") {
finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr]; // <<<
bigScalCntr++;
}
else {
//replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
finlOutPut[b] = ' ';
bigScalCntr++; //advance the counter
}
}
//convert The output Arry to , more printable string
var nonzero = false; // <<<
for(n = 0; n<finlOutPut.length; n++){
if (finlOutPut[n] != ' ') { // <<<
if (nonzero) output += ' , '; // <<<
nonzero = true; // <<<
} // <<<
output +=finlOutPut[n];
}
Your problem is already solved but I am posting another way of doing it just for reference.
The code was written to be tested on node.js, but the functions should work fine when called within the browser. Also, this only handles the range [0,1000000], but can be easily adapted for bigger ranges.
// actual conversion code starts here
var ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
var teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
function convert_millions(num) {
if (num >= 1000000) {
return convert_millions(Math.floor(num / 1000000)) + " million " + convert_thousands(num % 1000000);
} else {
return convert_thousands(num);
}
}
function convert_thousands(num) {
if (num >= 1000) {
return convert_hundreds(Math.floor(num / 1000)) + " thousand " + convert_hundreds(num % 1000);
} else {
return convert_hundreds(num);
}
}
function convert_hundreds(num) {
if (num > 99) {
return ones[Math.floor(num / 100)] + " hundred " + convert_tens(num % 100);
} else {
return convert_tens(num);
}
}
function convert_tens(num) {
if (num < 10) return ones[num];
else if (num >= 10 && num < 20) return teens[num - 10];
else {
return tens[Math.floor(num / 10)] + " " + ones[num % 10];
}
}
function convert(num) {
if (num == 0) return "zero";
else return convert_millions(num);
}
//end of conversion code
//testing code begins here
function main() {
var cases = [0, 1, 2, 7, 10, 11, 12, 13, 15, 19, 20, 21, 25, 29, 30, 35, 50, 55, 69, 70, 99, 100, 101, 119, 510, 900, 1000, 5001, 5019, 5555, 10000, 11000, 100000, 199001, 1000000, 1111111, 190000009];
for (var i = 0; i < cases.length; i++) {
console.log(cases[i] + ": " + convert(cases[i]));
}
}
main();
I know this problem had solved 3 years ago. I am posting this SPECIALLY FOR INDIAN DEVELOPERS
After spending some time in googling and playing with others code i made a quick fix and reusable function works well for numbers upto 99,99,99,999. use : number2text(1234.56); will return ONE THOUSAND TWO HUNDRED AND THIRTY-FOUR RUPEE AND FIFTY-SIX PAISE ONLY . enjoy !
function number2text(value) {
var fraction = Math.round(frac(value)*100);
var f_text = "";
if(fraction > 0) {
f_text = "AND "+convert_number(fraction)+" PAISE";
}
return convert_number(value)+" RUPEE "+f_text+" ONLY";
}
function frac(f) {
return f % 1;
}
function convert_number(number)
{
if ((number < 0) || (number > 999999999))
{
return "NUMBER OUT OF RANGE!";
}
var Gn = Math.floor(number / 10000000); /* Crore */
number -= Gn * 10000000;
var kn = Math.floor(number / 100000); /* lakhs */
number -= kn * 100000;
var Hn = Math.floor(number / 1000); /* thousand */
number -= Hn * 1000;
var Dn = Math.floor(number / 100); /* Tens (deca) */
number = number % 100; /* Ones */
var tn= Math.floor(number / 10);
var one=Math.floor(number % 10);
var res = "";
if (Gn>0)
{
res += (convert_number(Gn) + " CRORE");
}
if (kn>0)
{
res += (((res=="") ? "" : " ") +
convert_number(kn) + " LAKH");
}
if (Hn>0)
{
res += (((res=="") ? "" : " ") +
convert_number(Hn) + " THOUSAND");
}
if (Dn)
{
res += (((res=="") ? "" : " ") +
convert_number(Dn) + " HUNDRED");
}
var ones = Array("", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX","SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN","FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN","NINETEEN");
var tens = Array("", "", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY","SEVENTY", "EIGHTY", "NINETY");
if (tn>0 || one>0)
{
if (!(res==""))
{
res += " AND ";
}
if (tn < 2)
{
res += ones[tn * 10 + one];
}
else
{
res += tens[tn];
if (one>0)
{
res += ("-" + ones[one]);
}
}
}
if (res=="")
{
res = "zero";
}
return res;
}
Indian Version
Updated version of #jasonhao 's answer for Indian currency
function intToEnglish(number) {
var NS = [
{ value: 10000000, str: "Crore" },
{ value: 100000, str: "Lakh" },
{ value: 1000, str: "Thousand" },
{ value: 100, str: "Hundred" },
{ value: 90, str: "Ninety" },
{ value: 80, str: "Eighty" },
{ value: 70, str: "Seventy" },
{ value: 60, str: "Sixty" },
{ value: 50, str: "Fifty" },
{ value: 40, str: "Forty" },
{ value: 30, str: "Thirty" },
{ value: 20, str: "Twenty" },
{ value: 19, str: "Nineteen" },
{ value: 18, str: "Eighteen" },
{ value: 17, str: "Seventeen" },
{ value: 16, str: "Sixteen" },
{ value: 15, str: "Fifteen" },
{ value: 14, str: "Fourteen" },
{ value: 13, str: "Thirteen" },
{ value: 12, str: "Twelve" },
{ value: 11, str: "Eleven" },
{ value: 10, str: "Ten" },
{ value: 9, str: "Nine" },
{ value: 8, str: "Eight" },
{ value: 7, str: "Seven" },
{ value: 6, str: "Six" },
{ value: 5, str: "Five" },
{ value: 4, str: "Four" },
{ value: 3, str: "Three" },
{ value: 2, str: "Two" },
{ value: 1, str: "One" }
];
var result = '';
for (var n of NS) {
if (number >= n.value) {
if (number <= 99) {
result += n.str;
number -= n.value;
if (number > 0) result += ' ';
} else {
var t = Math.floor(number / n.value);
// console.log(t);
var d = number % n.value;
if (d > 0) {
return intToEnglish(t) + ' ' + n.str + ' ' + intToEnglish(d);
} else {
return intToEnglish(t) + ' ' + n.str;
}
}
}
}
return result;
}
console.log(intToEnglish(99))
console.log(intToEnglish(991199))
console.log(intToEnglish(123456799))
There are JS library for en_US and cs_CZ.
You can use it standalone or as Node module.
Numbers2Words
Here, I wrote an alternative solution:
1) The object containing the string constants:
var NUMBER2TEXT = {
ones: ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
tens: ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'],
sep: ['', ' thousand ', ' million ', ' billion ', ' trillion ', ' quadrillion ', ' quintillion ', ' sextillion ']
};
2) The actual code:
(function( ones, tens, sep ) {
var input = document.getElementById( 'input' ),
output = document.getElementById( 'output' );
input.onkeyup = function() {
var val = this.value,
arr = [],
str = '',
i = 0;
if ( val.length === 0 ) {
output.textContent = 'Please type a number into the text-box.';
return;
}
val = parseInt( val, 10 );
if ( isNaN( val ) ) {
output.textContent = 'Invalid input.';
return;
}
while ( val ) {
arr.push( val % 1000 );
val = parseInt( val / 1000, 10 );
}
while ( arr.length ) {
str = (function( a ) {
var x = Math.floor( a / 100 ),
y = Math.floor( a / 10 ) % 10,
z = a % 10;
return ( x > 0 ? ones[x] + ' hundred ' : '' ) +
( y >= 2 ? tens[y] + ' ' + ones[z] : ones[10*y + z] );
})( arr.shift() ) + sep[i++] + str;
}
output.textContent = str;
};
})( NUMBER2TEXT.ones, NUMBER2TEXT.tens, NUMBER2TEXT.sep );
Live demo: http://jsfiddle.net/j5kdG/
A version with a compact object - for numbers from zero to 999.
function wordify(n) {
var word = [],
numbers = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', t3: 'Thir', t5: 'Fif', t8: 'Eigh', 20: 'Twenty' },
hundreds = 0 | (n % 1000) / 100,
tens = 0 | (n % 100) / 10,
ones = n % 10,
part;
if (n === 0) return 'Zero';
if (hundreds) word.push(numbers[hundreds] + ' Hundred');
if (tens === 0) {
word.push(numbers[ones]);
} else if (tens === 1) {
word.push(numbers['1' + ones] || (numbers['t' + ones] || numbers[ones]) + 'teen');
} else {
part = numbers[tens + '0'] || (numbers['t' + tens] || numbers[tens]) + 'ty';
word.push(numbers[ones] ? part + '-' + numbers[ones] : part);
}
return word.join(' ');
}
var i,
output = document.getElementById('out');
for (i = 0; i < 1e3; i++) output.innerHTML += wordify(i) + '\n';
<pre id="out"></pre>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
var th = ['', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion'];
var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function update(){
var numString = document.getElementById('number').value;
if (numString == '0') {
document.getElementById('container').innerHTML = 'Zero';
return;
}
if (numString == 0) {
document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
return;
}
var output = toWords(numString);
//print the output
document.getElementById('container').innerHTML = output;
}
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
} else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
} else if (n[i] != 0) {
str += dg[n[i]] + ' ';
if ((x - i) % 3 == 0) str += 'hundred ';
sk = 1;
}
if ((x - i) % 3 == 1) {
if (sk) str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
return str.replace(/\s+/g, ' ');
}
</script>
</head>
<body>
<input type="text"
id="number"
size="70"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"/>
<br/>
<div id="container">Here The Numbers Printed</div>
</body>
</html>
Try this,convert number to words
function convert(number) {
if (number < 0) {
console.log("Number Must be greater than zero = " + number);
return "";
}
if (number > 100000000000000000000) {
console.log("Number is out of range = " + number);
return "";
}
if (!is_numeric(number)) {
console.log("Not a number = " + number);
return "";
}
var quintillion = Math.floor(number / 1000000000000000000); /* quintillion */
number -= quintillion * 1000000000000000000;
var quar = Math.floor(number / 1000000000000000); /* quadrillion */
number -= quar * 1000000000000000;
var trin = Math.floor(number / 1000000000000); /* trillion */
number -= trin * 1000000000000;
var Gn = Math.floor(number / 1000000000); /* billion */
number -= Gn * 1000000000;
var million = Math.floor(number / 1000000); /* million */
number -= million * 1000000;
var Hn = Math.floor(number / 1000); /* thousand */
number -= Hn * 1000;
var Dn = Math.floor(number / 100); /* Tens (deca) */
number = number % 100; /* Ones */
var tn = Math.floor(number / 10);
var one = Math.floor(number % 10);
var res = "";
if (quintillion > 0) {
res += (convert_number(quintillion) + " quintillion");
}
if (quar > 0) {
res += (convert_number(quar) + " quadrillion");
}
if (trin > 0) {
res += (convert_number(trin) + " trillion");
}
if (Gn > 0) {
res += (convert_number(Gn) + " billion");
}
if (million > 0) {
res += (((res == "") ? "" : " ") + convert_number(million) + " million");
}
if (Hn > 0) {
res += (((res == "") ? "" : " ") + convert_number(Hn) + " Thousand");
}
if (Dn) {
res += (((res == "") ? "" : " ") + convert_number(Dn) + " hundred");
}
var ones = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", "Nineteen");
var tens = Array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eigthy", "Ninety");
if (tn > 0 || one > 0) {
if (!(res == "")) {
res += " and ";
}
if (tn < 2) {
res += ones[tn * 10 + one];
} else {
res += tens[tn];
if (one > 0) {
res += ("-" + ones[one]);
}
}
}
if (res == "") {
console.log("Empty = " + number);
res = "";
}
return res;
}
function is_numeric(mixed_var) {
return (typeof mixed_var === 'number' || typeof mixed_var === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}
function intToEnglish(number){
var NS = [
{value: 1000000000000000000000, str: "sextillion"},
{value: 1000000000000000000, str: "quintillion"},
{value: 1000000000000000, str: "quadrillion"},
{value: 1000000000000, str: "trillion"},
{value: 1000000000, str: "billion"},
{value: 1000000, str: "million"},
{value: 1000, str: "thousand"},
{value: 100, str: "hundred"},
{value: 90, str: "ninety"},
{value: 80, str: "eighty"},
{value: 70, str: "seventy"},
{value: 60, str: "sixty"},
{value: 50, str: "fifty"},
{value: 40, str: "forty"},
{value: 30, str: "thirty"},
{value: 20, str: "twenty"},
{value: 19, str: "nineteen"},
{value: 18, str: "eighteen"},
{value: 17, str: "seventeen"},
{value: 16, str: "sixteen"},
{value: 15, str: "fifteen"},
{value: 14, str: "fourteen"},
{value: 13, str: "thirteen"},
{value: 12, str: "twelve"},
{value: 11, str: "eleven"},
{value: 10, str: "ten"},
{value: 9, str: "nine"},
{value: 8, str: "eight"},
{value: 7, str: "seven"},
{value: 6, str: "six"},
{value: 5, str: "five"},
{value: 4, str: "four"},
{value: 3, str: "three"},
{value: 2, str: "two"},
{value: 1, str: "one"}
];
var result = '';
for (var n of NS) {
if(number>=n.value){
if(number<=20){
result += n.str;
number -= n.value;
if(number>0) result += ' ';
}else{
var t = Math.floor(number / n.value);
var d = number % n.value;
if(d>0){
return intToEnglish(t) + ' ' + n.str +' ' + intToEnglish(d);
}else{
return intToEnglish(t) + ' ' + n.str;
}
}
}
}
return result;
}
This is a simple ES6+ number to words function. You can simply add 'illions' array to extend digits. American English version.
(no 'and' before the end)
// generic number to words
let digits = ['','one','two','three','four', 'five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
let ties = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
let illions = ['', 'thousand', 'million', 'billion', 'trillion'].reverse()
let join = (a, s) => a.filter(v => v).join(s || ' ')
let tens = s =>
digits[s] ||
join([ties[s[0]], digits[s[1]]], '-') // 21 -> twenty-one
let hundreds = s =>
join(
(s[0] !== '0' ? [digits[s[0]], 'hundred'] : [])
.concat( tens(s.substr(1,2)) ) )
let re = '^' + '(\\d{3})'.repeat(illions.length) + '$'
let numberToWords = n =>
// to filter non number or '', null, undefined, false, NaN
isNaN(Number(n)) || !n && n !== 0
? 'not a number'
: Number(n) === 0
? 'zero'
: Number(n) >= 10 ** (illions.length * 3)
? 'too big'
: String(n)
.padStart(illions.length * 3, '0')
.match(new RegExp(re))
.slice(1, illions.length + 1)
.reduce( (a, v, i) => v === '000' ? a : join([a, hundreds(v), illions[i]]), '')
// just for this question.
let update = () => {
let value = document.getElementById('number').value
document.getElementById('container').innerHTML = numberToWords(value)
}
Here's a solution that will handle any integer value that fit's in a string. I've defined number scales up to "decillion", so this solution should be accurate up to 999 decillion. After which you get things like "one thousand decillion" and so on.
JavaScript numbers start to fail around "999999999999999" so the convert function works with strings of numbers only.
Examples:
convert("365");
//=> "three hundred sixty-five"
convert("10000000000000000000000000000230001010109");
//=> "ten thousand decillion two hundred thirty billion one million ten thousand one hundred nine"
Code:
var lt20 = ["", "one", "two", "three", "four", "five", "six", "seven","eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ],
tens = ["", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eightty", "ninety" ],
scales = ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion" ],
max = scales.length * 3;
function convert(val) {
var len;
// special cases
if (val[0] === "-") { return "negative " + convert(val.slice(1)); }
if (val === "0") { return "zero"; }
val = trim_zeros(val);
len = val.length;
// general cases
if (len < max) { return convert_lt_max(val); }
if (len >= max) { return convert_max(val); }
}
function convert_max(val) {
return split_rl(val, max)
.map(function (val, i, arr) {
if (i < arr.length - 1) {
return convert_lt_max(val) + " " + scales.slice(-1);
}
return convert_lt_max(val);
})
.join(" ");
}
function convert_lt_max(val) {
var l = val.length;
if (l < 4) {
return convert_lt1000(val).trim();
} else {
return split_rl(val, 3)
.map(convert_lt1000)
.reverse()
.map(with_scale)
.reverse()
.join(" ")
.trim();
}
}
function convert_lt1000(val) {
var rem, l;
val = trim_zeros(val);
l = val.length;
if (l === 0) { return ""; }
if (l < 3) { return convert_lt100(val); }
if (l === 3) { //less than 1000
rem = val.slice(1);
if (rem) {
return lt20[val[0]] + " hundred " + convert_lt1000(rem);
} else {
return lt20[val[0]] + " hundred";
}
}
}
function convert_lt100(val) {
if (is_lt20(val)) { // less than 20
return lt20[val];
} else if (val[1] === "0") {
return tens[val[0]];
} else {
return tens[val[0]] + "-" + lt20[val[1]];
}
}
function split_rl(str, n) {
// takes a string 'str' and an integer 'n'. Splits 'str' into
// groups of 'n' chars and returns the result as an array. Works
// from right to left.
if (str) {
return Array.prototype.concat
.apply(split_rl(str.slice(0, (-n)), n), [str.slice(-n)]);
} else {
return [];
}
}
function with_scale(str, i) {
var scale;
if (str && i > (-1)) {
scale = scales[i];
if (scale !== undefined) {
return str.trim() + " " + scale;
} else {
return convert(str.trim());
}
} else {
return "";
}
}
function trim_zeros(val) {
return val.replace(/^0*/, "");
}
function is_lt20(val) {
return parseInt(val, 10) < 20;
}
I've modified the posting from Šime Vidas - http://jsfiddle.net/j5kdG/
To include dollars, cents, commas and "and" in the appropriate places.
There's an optional ending if it requires "zero cents" or no mention of cents if 0.
This function structure did my head in a bit but I learned heaps. Thanks Sime.
Someone might find a better way of processing this.
Code:
var str='';
var str2='';
var str3 =[];
function convertNum(inp,end){
str2='';
str3 = [];
var NUMBER2TEXT = {
ones: ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
tens: ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'],
sep: ['', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion', ' sextillion']
};
(function( ones, tens, sep ) {
var vals = inp.split("."),val,pos,postsep=' ';
for (p in vals){
val = vals[p], arr = [], str = '', i = 0;
if ( val.length === 0 ) {return 'No value';}
val = parseInt( (p==1 && val.length===1 )?val*10:val, 10 );
if ( isNaN( val ) || p>=2) {return 'Invalid value'; }
while ( val ) {
arr.push( val % 1000 );
val = parseInt( val / 1000, 10 );
}
pos = arr.length;
function trimx (strx) {
return strx.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function seps(sepi,i){
var s = str3.length
if (str3[s-1][0]){
if (str3[s-2][1] === str3[s-1][0]){
str = str.replace(str3[s-2][1],'')
}
}
var temp = str.split(sep[i-2]);
if (temp.length > 1){
if (trimx(temp[0]) ==='' && temp[1].length > 1 ){
str = temp[1];
}
}
return sepi + str ;
}
while ( arr.length ) {
str = (function( a ) {
var x = Math.floor( a / 100 ),
y = Math.floor( a / 10 ) % 10,
z = a % 10;
postsep = (arr.length != 0)?', ' : ' ' ;
if ((x+y+z) === 0){
postsep = ' '
}else{
if (arr.length == pos-1 && x===0 && pos > 1 ){
postsep = ' and '
}
}
str3.push([trimx(str)+"",trimx(sep[i])+""]);
return (postsep)+( x > 0 ? ones[x] + ' hundred ' + (( x == 0 && y >= 0 || z >0 )?' and ':' ') : ' ' ) +
( y >= 2 ? tens[y] + ((z===0)?' ':'-') + ones[z] : ones[10*y + z] );
})( arr.shift() ) +seps( sep[i++] ,i ) ;
}
if (p==0){ str2 += str + ' dollars'}
if (p==1 && !end){str2 += (str!='')?' and '+ str + ' cents':'' }
if (p==1 && end ){str2 += ' and ' + ((str==='')?'zero':str) + ' cents '}
}
})( NUMBER2TEXT.ones , NUMBER2TEXT.tens , NUMBER2TEXT.sep );
this is the solution for french language
it's a fork for #gandil response
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
var th = ['', ' mille', ' millions', ' milliards', ' billions', ' mille-billions', ' trillion'];
var dg = ['zéro', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf'];
var tn = ['dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf'];
var tw = ['vingt', 'trente', 'quarante', 'cinquante', 'soixante', 'soixante-dix', 'quatre-vingts', 'quatre-vingt-dix'];
function update(){
var numString = document.getElementById('number').value;
if (numString == '0') {
document.getElementById('container').innerHTML = 'Zéro';
return;
}
if (numString == 0) {
document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
return;
}
var output = toWords(numString);
//output.split('un mille').join('msille ');
//output.replace('un cent', 'cent ');
//print the output
//if(output.length == 4){output = 'sss';}
document.getElementById('container').innerHTML = output;
}
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
} else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
} else if (n[i] != 0) {
str += dg[n[i]] + ' ';
//if((dg[n[i]] == 'un') && ((x - i) / 3 == 1)){str = 'cent ';}
if ((x - i) % 3 == 0) {str += 'cent ';}
sk = 1;
}
if ((x - i) % 3 == 1) {
//test
if((x - i - 1) / 3 == 1){
var long = str.length;
subs = str.substr(long-3);
if(subs.search("un")!= -1){
//str += 'OK';
str = str.substr(0, long-4);
}
}
//test
if (sk) str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
//if(str.length == 4){}
str.replace(/\s+/g, ' ');
return str.split('un cent').join('cent ');
//return str.replace('un cent', 'cent ');
}
</script>
</head>
<body>
<input type="text"
id="number"
size="70"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"/>
<br/>
<div id="container">Here The Numbers Printed</div>
</body>
</html>
i hope it will help
A little code snippet for INDONESIAN DEVELOPER to translate numeric value into verbal spelling (minimized by hand, only 576 bytes, requires ES6+)...
const terbilang=(x,nol='---',min='minus')=>{const S=['','satu','dua','tiga','empat','lima','enam','tujuh','delapan','sembilan'],K=['','ribu','juta','miliar','triliun','kuadriliun'],s=[];if(!x)return nol;if(x<0){if(min)s=[min];x=-x}for(let k=0;x;k++){let g=x%1e3;if(g===1&&k===1)s.unshift('seribu');else{let u=g>99?[(g>199?S[g/100|0]+' ':'se')+'ratus']:[];if(g%=100){if(g>9&&g<20)u.push(g<11?'sepuluh':(g<12?'se':S[g%10]+' ')+'belas');else{if(g>19)u.push(S[g/10|0]+' puluh');if(g%=10)u.push(S[g])}}k&&u.push(K[k]);s.unshift(u.join(' '))}x=Math.floor(x/1e3)}return s.join(' ')};
function toWords(...x) {
let space = /\s/g;
let digit = /\d/g;
let trio = /.../g;
let unit = ' one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'.split(space);
let ten = ' twenty thirty forty fifty sixty seventy eighty ninety'.split(space);
let scale = ' thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion'.split(space);
let d = digit.test(x) ? String(x).match(digit) : ['0'];
while (d.length % 3) d.unshift('0');
d = d.join('').match(trio).map(function verbose(string) {
let number = Number(string);
return (number < 20) ?
unit[number] :
(number < 100) ?
[ten[Number(string.slice(0, -1))], verbose(string.slice(-1))].filter(Boolean).join('-') :
[verbose(string.slice(0, -2)), 'hundred', verbose(string.slice(-2))].filter(Boolean).join(' ');
}).reverse().map(function(v, i, a) {
return v ? [v, scale[i]].filter(Boolean).join(' ') : v;
}).reverse().filter(Boolean).join(', ');
return d ? d : 'zero';
}
toWords('14,702,000,583,690,010');
// 'fourteen quadrillion, seven hundred two trillion, five hundred eighty-three million, six hundred ninety thousand, ten'
Update Feb 2022
A simple and short Javascript function to do the conversion of numbers (integers) to words in English (US System) and give the correct results is included below using a forEach() loop with the String Triplets Array method.
The number is first converted into a string triplet array using:
num= ("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
The string array is then easily decoded into numbers.
For example, the number 1234567 is converted into an array of string triplets:
[ '001', '234', '567' ]
Each element is then scanned from left to right by the forEach() loop.
This is a far better solution than using a for loop that I had proposed 2 years ago.
You can increase the scale array above the 'Quadrillion' if you prefer.
If the input number is too large, then pass it as a "string".
Test cases are also included.
/********************************************************
* #function : numToWords(number)
* #purpose : Converts Unsigned Integers to Words
* #version : 1.50
* #author : Mohsen Alyafei
* #licence : MIT
* #date : 26 Feb 2022
* #param : {number} [integer numeric or string]
* #returns : {string} The wordified number string
********************************************************/
//==============================================================
function numToWords(num = 0) {
if (num == 0) return "Zero";
num= ("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
let out="",
T10s=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
T20s=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],
sclT=["","Thousand","Million","Billion","Trillion","Quadrillion"];
return num.forEach((n,i) => {
if (+n) {
let hund=+n[0], ten=+n.substring(1), scl=sclT[num.length-i-1];
out+=(out?" ":"")+(hund?T10s[hund]+" Hundred":"")+(hund && ten?" ":"")+(ten<20?T10s[ten]:T20s[+n[1]]+(+n[2]?"-":"")+T10s[+n[2]]);
out+=(out && scl?" ":"")+scl;
}}),out;
}
//==============================================================
//=========================================
// Test Code
//=========================================
var r=0; // test tracker
r |= test(0,"Zero");
r |= test(5,"Five");
r |= test(10,"Ten");
r |= test(19,"Nineteen");
r |= test(33,"Thirty-Three");
r |= test(100,"One Hundred");
r |= test(111,"One Hundred Eleven");
r |= test(890,"Eight Hundred Ninety");
r |= test(1234,"One Thousand Two Hundred Thirty-Four");
r |= test(12345,"Twelve Thousand Three Hundred Forty-Five");
r |= test(123456,"One Hundred Twenty-Three Thousand Four Hundred Fifty-Six");
r |= test(1234567,"One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven");
r |= test(12345678,"Twelve Million Three Hundred Forty-Five Thousand Six Hundred Seventy-Eight");
r |= test(123456789,"One Hundred Twenty-Three Million Four Hundred Fifty-Six Thousand Seven Hundred Eighty-Nine");
r |= test(1234567890,"One Billion Two Hundred Thirty-Four Million Five Hundred Sixty-Seven Thousand Eight Hundred Ninety");
r |= test(1001,"One Thousand One");
r |= test(10001,"Ten Thousand One");
r |= test(100001,"One Hundred Thousand One");
r |= test(1000001,"One Million One");
r |= test(10000001,"Ten Million One");
r |= test(100000001,"One Hundred Million One");
r |= test(12012,"Twelve Thousand Twelve");
r |= test(120012,"One Hundred Twenty Thousand Twelve");
r |= test(1200012,"One Million Two Hundred Thousand Twelve");
r |= test(12000012,"Twelve Million Twelve");
r |= test(120000012,"One Hundred Twenty Million Twelve");
r |= test(75075,"Seventy-Five Thousand Seventy-Five");
r |= test(750075,"Seven Hundred Fifty Thousand Seventy-Five");
r |= test(7500075,"Seven Million Five Hundred Thousand Seventy-Five");
r |= test(75000075,"Seventy-Five Million Seventy-Five");
r |= test(750000075,"Seven Hundred Fifty Million Seventy-Five");
r |= test(1000,"One Thousand");
r |= test(1000000,"One Million");
r |= test(1000000000,"One Billion");
r |= test(1000000000000,"One Trillion");
r |= test("1000000000000000","One Quadrillion");
if (r==0) console.log("All Test Cases Passed.");
function test(n,should) {
let result = numToWords(n);
if (result !== should) {console.log(`${n} Output : ${result}\n${n} Should be: ${should}`);return 1;}
}
I would like to point out that the original logic fails for values between x11-x19, where x >= 1. For example, 118 returns "one hundred eight". This is because these numbers are processed by the following code in triConvert():
//100 and more
if (numString.length == 3) {
output = ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output += ones[parseInt(numString.charAt(2))];
return output;
}
here, the character representing the tens digit is used to index the tens[] array, which has an empty string at index [1], so 118 become 108 in effect.
It might be better to deal with the hundreds (if any first), then run the ones and tens through the same logic. Instead of:
//the case of 10, 11, 12 ,13, .... 19
if (num < 20) {
output = ones[num];
return output;
}
//100 and more
if (numString.length == 3) {
output = ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output += ones[parseInt(numString.charAt(2))];
return output;
}
output += tens[parseInt(numString.charAt(0))];
output += ones[parseInt(numString.charAt(1))];
return output;
I would suggest:
// 100 and more
if ( numString.length == 3 )
{
output = hundreds[ parseInt( numString.charAt(0) ) ] + hundred ;
num = num % 100 ;
numString = num.toString() ;
}
if ( num < 20 )
{
output += ones[num] ;
}
else
{ // 20-99
output += tens[ parseInt( numString.charAt(0) ) ] ;
output += '-' + ones[ parseInt( numString.charAt(1) ) ] ;
}
return output;
It seems to me that the suggested code is both shorter and clearer, but I might be biased ;-)
Source: http://javascript.about.com/library/bltoword.htm
Smallest script that I found:
<script type="text/javascript" src="toword.js">
var words = toWords(12345);
console.log(words);
</script>
Enjoy!
I tried Muhammad's solution, but had some issues and wanted to use decimals so I made some changes and converted to coffeescript and angular. Please bear in mind that js and coffeescript are not my strong suits, so use with care.
$scope.convert = (number, upper=0) ->
number = +number
# console.log "inside convert and the number is: " + number
if number < 0
# console.log 'Number Must be greater than zero = ' + number
return ''
if number > 100000000000000000000
# console.log 'Number is out of range = ' + number
return ''
if isNaN(number)
console.log("NOT A NUMBER")
alert("Not a number = ")
return ''
else
console.log "at line 88 number is: " + number
quintillion = Math.floor(number / 1000000000000000000)
### quintillion ###
number -= quintillion * 1000000000000000000
quar = Math.floor(number / 1000000000000000)
# console.log "at line 94 number is: " + number
### quadrillion ###
number -= quar * 1000000000000000
trin = Math.floor(number / 1000000000000)
# console.log "at line 100 number is: " + number
### trillion ###
number -= trin * 1000000000000
Gn = Math.floor(number / 1000000000)
# console.log "at line 105 number is: " + number
### billion ###
number -= Gn * 1000000000
million = Math.floor(number / 1000000)
# console.log "at line 111 number is: " + number
### million ###
number -= million * 1000000
Hn = Math.floor(number / 1000)
# console.log "at line 117 number is: " + number
### thousand ###
number -= Hn * 1000
Dn = Math.floor(number / 100)
# console.log "at line 123 number is: " + number
### Tens (deca) ###
number = number % 100
# console.log "at line 128 number is: " + number
### Ones ###
tn = Math.floor(number / 10)
one = Math.floor(number % 10)
# tn = Math.floor(number / 1)
change = Math.round((number % 1) * 100)
res = ''
# console.log "before ifs"
if quintillion > 0
res += $scope.convert(quintillion) + ' Quintillion'
if quar > 0
res += $scope.convert(quar) + ' Quadrillion'
if trin > 0
res += $scope.convert(trin) + ' Trillion'
if Gn > 0
res += $scope.convert(Gn) + ' Billion'
if million > 0
res += (if res == '' then '' else ' ') + $scope.convert(million) + ' Million'
if Hn > 0
res += (if res == '' then '' else ' ') + $scope.convert(Hn) + ' Thousand'
if Dn
res += (if res == '' then '' else ' ') + $scope.convert(Dn) + ' Hundred'
# console.log "the result is: " + res
ones = Array('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eightteen', 'Nineteen')
tens = Array('', '', 'Twenty', 'Thirty', 'Fourty', 'Fifty', 'Sixty', 'Seventy', 'Eigthy', 'Ninety')
# console.log "the result at 161 is: " + res
if tn > 0 or one > 0
if !(res == '')
# res += ' and '
res += ' '
# console.log "the result at 164 is: " + res
if tn < 2
res += ones[tn * 10 + one]
# console.log "the result at 168is: " + res
else
res += tens[tn]
if one > 0
res += '-' + ones[one]
# console.log "the result at 173 is: " + res
if change > 0
if res == ''
res = change + "/100"
else
res += ' and ' + change + "/100"
if res == ''
console.log 'Empty = ' + number
res = ''
if +upper == 1
res = res.toUpperCase()
$scope.newCheck.amountInWords = res
return res
$scope.is_numeric = (mixed_var) ->
# console.log "mixed var is: " + mixed_var
(typeof mixed_var == 'number' or typeof mixed_var == 'string') and mixed_var != '' and !isNaN(mixed_var)
Here is another version from me with some unit tests.
Don't use it with numbers larger than Number.MAX_SAFE_INTEGER.
describe("English Numerals Converter", function () {
assertNumeral(0, "zero");
assertNumeral(1, "one");
assertNumeral(2, "two");
assertNumeral(3, "three");
assertNumeral(4, "four");
assertNumeral(5, "five");
assertNumeral(6, "six");
assertNumeral(7, "seven");
assertNumeral(8, "eight");
assertNumeral(9, "nine");
assertNumeral(10, "ten");
assertNumeral(11, "eleven");
assertNumeral(12, "twelve");
assertNumeral(13, "thirteen");
assertNumeral(14, "fourteen");
assertNumeral(15, "fifteen");
assertNumeral(16, "sixteen");
assertNumeral(17, "seventeen");
assertNumeral(18, "eighteen");
assertNumeral(19, "nineteen");
assertNumeral(20, "twenty");
assertNumeral(21, "twenty-one");
assertNumeral(22, "twenty-two");
assertNumeral(23, "twenty-three");
assertNumeral(30, "thirty");
assertNumeral(37, "thirty-seven");
assertNumeral(40, "forty");
assertNumeral(50, "fifty");
assertNumeral(60, "sixty");
assertNumeral(70, "seventy");
assertNumeral(80, "eighty");
assertNumeral(90, "ninety");
assertNumeral(99, "ninety-nine");
assertNumeral(100, "one hundred");
assertNumeral(101, "one hundred and one");
assertNumeral(102, "one hundred and two");
assertNumeral(110, "one hundred and ten");
assertNumeral(120, "one hundred and twenty");
assertNumeral(121, "one hundred and twenty-one");
assertNumeral(199, "one hundred and ninety-nine");
assertNumeral(200, "two hundred");
assertNumeral(999, "nine hundred and ninety-nine");
assertNumeral(1000, "one thousand");
assertNumeral(1001, "one thousand and one");
assertNumeral(1011, "one thousand and eleven");
assertNumeral(1111, "one thousand and one hundred and eleven");
assertNumeral(9999, "nine thousand and nine hundred and ninety-nine");
assertNumeral(10000, "ten thousand");
assertNumeral(20000, "twenty thousand");
assertNumeral(21000, "twenty-one thousand");
assertNumeral(90000, "ninety thousand");
assertNumeral(90001, "ninety thousand and one");
assertNumeral(90100, "ninety thousand and one hundred");
assertNumeral(90901, "ninety thousand and nine hundred and one");
assertNumeral(90991, "ninety thousand and nine hundred and ninety-one");
assertNumeral(90999, "ninety thousand and nine hundred and ninety-nine");
assertNumeral(91000, "ninety-one thousand");
assertNumeral(99999, "ninety-nine thousand and nine hundred and ninety-nine");
assertNumeral(100000, "one hundred thousand");
assertNumeral(999000, "nine hundred and ninety-nine thousand");
assertNumeral(1000000, "one million");
assertNumeral(10000000, "ten million");
assertNumeral(100000000, "one hundred million");
assertNumeral(1000000000, "one billion");
assertNumeral(1000000000000, "one trillion");
assertNumeral(1000000000000000, "one quadrillion");
assertNumeral(1000000000000000000, "one quintillion");
assertNumeral(1000000000000000000000, "one sextillion");
assertNumeral(-1, "minus one");
assertNumeral(-999, "minus nine hundred and ninety-nine");
function assertNumeral(number, numeral) {
it(number + " is " + numeral, function () {
expect(convert(number)).toBe(numeral);
});
}
});
function convert(n) {
let NUMERALS = [
{value: 1000000000000000000000, str: "sextillion"},
{value: 1000000000000000000, str: "quintillion"},
{value: 1000000000000000, str: "quadrillion"},
{value: 1000000000000, str: "trillion"},
{value: 1000000000, str: "billion"},
{value: 1000000, str: "million"},
{value: 1000, str: "thousand"},
{value: 100, str: "hundred"},
{value: 90, str: "ninety"},
{value: 80, str: "eighty"},
{value: 70, str: "seventy"},
{value: 60, str: "sixty"},
{value: 50, str: "fifty"},
{value: 40, str: "forty"},
{value: 30, str: "thirty"},
{value: 20, str: "twenty"},
{value: 19, str: "nineteen"},
{value: 18, str: "eighteen"},
{value: 17, str: "seventeen"},
{value: 16, str: "sixteen"},
{value: 15, str: "fifteen"},
{value: 14, str: "fourteen"},
{value: 13, str: "thirteen"},
{value: 12, str: "twelve"},
{value: 11, str: "eleven"},
{value: 10, str: "ten"},
{value: 9, str: "nine"},
{value: 8, str: "eight"},
{value: 7, str: "seven"},
{value: 6, str: "six"},
{value: 5, str: "five"},
{value: 4, str: "four"},
{value: 3, str: "three"},
{value: 2, str: "two"},
{value: 1, str: "one"}
];
if (n < 0) {
return "minus " + convert(-n);
} else if (n === 0) {
return "zero";
} else {
let result = "";
for (let numeral of NUMERALS) {
if (n >= numeral.value) {
if (n < 100) {
result += numeral.str;
n -= numeral.value;
if (n > 0) result += "-";
} else {
let times = Math.floor(n / numeral.value);
result += convert(times) + " " + numeral.str;
n -= numeral.value * times;
if (n > 0) result += " and ";
}
}
}
return result;
}
}
<script src="http://www.ittutorials.in/js/demo/numtoword.js" type="text/javascript"></script>
HTML - Convert numbers to words using JavaScript</h1>
<input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);" onkeyup="NumToWord(this.value,'divDisplayWords');"
maxlength="9" style="background-color: #efefef; border: 2px solid #CCCCC; font-size: large" />
<br />
<br />
<div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;">
</div>
I think, I have solution that's simpler and easier to understand; it goes by slicing the number, it works up to 99 lakhs crore.
function convert_to_word(num, ignore_ten_plus_check) {
var ones = [];
var tens = [];
var ten_plus = [];
ones["1"] = "one";
ones["2"] = "two";
ones["3"] = "three";
ones["4"] = "four";
ones["5"] = "five";
ones["6"] = "six";
ones["7"] = "seven";
ones["8"] = "eight";
ones["9"] = "nine";
ten_plus["10"] = "ten";
ten_plus["11"] = "eleven";
ten_plus["12"] = "twelve";
ten_plus["13"] = "thirteen";
ten_plus["14"] = "fourteen";
ten_plus["15"] = "fifteen";
ten_plus["16"] = "sixteen";
ten_plus["17"] = "seventeen";
ten_plus["18"] = "eighteen";
ten_plus["19"] = "nineteen";
tens["1"] = "ten";
tens["2"] = "twenty";
tens["3"] = "thirty";
tens["4"] = "fourty";
tens["5"] = "fifty";
tens["6"] = "sixty";
tens["7"] = "seventy";
tens["8"] = "eighty";
tens["9"] = "ninety";
var len = num.length;
if(ignore_ten_plus_check != true && len >= 2) {
var ten_pos = num.slice(len - 2, len - 1);
if(ten_pos == "1") {
return ten_plus[num.slice(len - 2, len)];
} else if(ten_pos != 0) {
return tens[num.slice(len - 2, len - 1)] + " " + ones[num.slice(len - 1, len)];
}
}
return ones[num.slice(len - 1, len)];
}
function get_rupees_in_words(str, recursive_call_count) {
if(recursive_call_count > 1) {
return "conversion is not feasible";
}
var len = str.length;
var words = convert_to_word(str, false);
if(len == 2 || len == 1) {
if(recursive_call_count == 0) {
words = words +" rupees";
}
return words;
}
if(recursive_call_count == 0) {
words = " and " + words +" rupees";
}
var hundred = convert_to_word(str.slice(0, len-2), true);
words = hundred != undefined ? hundred + " hundred " + words : words;
if(len == 3) {
return words;
}
var thousand = convert_to_word(str.slice(0, len-3), false);
words = thousand != undefined ? thousand + " thousand " + words : words;
if(len <= 5) {
return words;
}
var lakh = convert_to_word(str.slice(0, len-5), false);
words = lakh != undefined ? lakh + " lakh " + words : words;
if(len <= 7) {
return words;
}
recursive_call_count = recursive_call_count + 1;
return get_rupees_in_words(str.slice(0, len-7), recursive_call_count) + " crore " + words;
}
Please check out my code pen
If anybody ever wants to do this but in Spanish (en español), here's my code based on Hardik's
function num2str(num, moneda) {
moneda = moneda || (num !== 1 ? "pesos" : "peso");
var fraction = Math.round(__cf_frac(num) * 100);
var f_text = " (" + pad(fraction, 2) + "/100 M.N.)";
return __cf_convert_number(num) + " " + moneda + f_text;
}
function __cf_frac(f) {
return f % 1;
}
function __cf_convert_number(number) {
if ((number < 0) || (number > 999999999)) {
throw Error("N\u00famero fuera de rango");
}
var millon = Math.floor(number / 1000000);
number -= millon * 1000000;
var cientosDeMiles = Math.floor(number / 100000);
number -= cientosDeMiles * 100000;
var miles = Math.floor(number / 1000);
number -= miles * 1000;
var centenas = Math.floor(number / 100);
number = number % 100;
var tn = Math.floor(number / 10);
var one = Math.floor(number % 10);
var res = "";
var cientos = Array("", "cien", "doscientos", "trescientos", "cuatrocientos", "quinientos", "seiscientos", "setecientos", "ochocientos", "novecientos");
if (millon > 0) {
res += (__cf_convert_number(millon) + (millon === 1 ? " mill\u00f3n" : " millones"));
}
if (cientosDeMiles > 0) {
res += (((res == "") ? "" : " ") +
cientos[cientosDeMiles] + (miles > 0 || centenas > 0 || tn > 0 || one < 0 ? (cientosDeMiles == 1 ? "to " : " ") : ""));
}
if (miles > 0) {
res += (((res == "") ? "" : " ") +
__cf_convert_number(miles) + " mil");
}
if (centenas) {
res += (((res == "") ? "" : " ") +
cientos[centenas] + (tn > 0 || one > 0 ? (centenas > 1 ? " " : "to ") : ""));
}
var ones = Array("", "un", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve");
var tens = Array("", "", "veinte", "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", "noventa");
if (tn > 0 || one > 0) {
if (tn < 2) {
res += ones[tn * 10 + one];
}
else {
if (tn === 2 && one > 0)
res += "veinti" + ones[one];
else {
res += tens[tn];
if (one > 0) {
res += (" y " + ones[one]);
}
}
}
}
if (res == "") {
res = "cero";
}
return res.replace(" ", " ");
}
function pad(num, largo, char) {
char = char || '0';
num = num + '';
return num.length >= largo ? num : new Array(largo - num.length + 1).join(char) + num;
}
Result:
num2str(123456789)
"ciento veintitres millones cuatrocientos cincuenta y seis mil setecientos ochenta y nueve pesos (00/100 M.N.)"
I am providing here my solution for converting numbers to the equivalent English words using the Single Loop String Triplets (SLST) Method which I have published and explained in detail here at Code Review with illustration graphics.
Simple Number to Words using a Single Loop String Triplets in JavaScript
The concept is simple and easily coded and is also very efficient and fast. The code is very short compared with other alternative methods described in this article.
The concept also permits the conversion of very vary large numbers as it does not rely on using the numeric/math function of the language and therefore avoids any limitations.
The Scale Array may be increased by adding more scale names if required after "Decillion".
A sample test function is provided below to generate numbers from 1 to 1099 as an example.
A full fancy version is available that caters for adding the word "and" and commas between the scales and numbers to align with the UK and US ways of spelling the numbers.
Hope this is useful.
/************************************************************/
function NumToWordsInt(NumIn) {
/************************************************************
* Convert Integer Numbers to English Words
* Using the Single Loop String Triplets Method
* #Param : {Number} The number to be converted
* For large numbers use a string
* #Return: {String} Wordified Number (Number in English Words)
* #Author: Mohsen Alyafei 10 July 2019
* #Notes : Call separately for whole and for fractional parts.
* Scale Array may be increased by adding more scale
* names if required after Decillion.
/************************************************************/
if (NumIn==0) return "Zero";
var Ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"],
Tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"],
Scale = ["", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion"],
N1, N2, Sep, j, i, h, Trplt, tns="", NumAll = "";
NumIn += ""; // Make NumIn a String
//----------------- code starts -------------------
NumIn = "0".repeat(NumIn.length * 2 % 3) + NumIn; //Create shortest string triplets 0 padded
j = 0; //Start with the highest triplet from LH
for (i = NumIn.length / 3 - 1; i >= 0; i--) { //Loop thru number of triplets from LH most
Trplt = NumIn.substring(j, j + 3); //Get a triplet number starting from LH
if (Trplt !="000") { //Skip empty trplets
Sep = Trplt[2] !="0" ? "-":" "; //Dash only for 21 to 99
N1 = Number(Trplt[0]); //Get Hundreds digit
N2 = Number(Trplt.substr(1)); //Get 2 lowest digits (00 to 99)
tns = N2 > 19 ? Tens[Number(Trplt[1])] + Sep + Ones[Number(Trplt[2])] : Ones[N2];
NumAll += ((h = N1>0 ? Ones[N1] + " Hundred": "") + " " + tns).trim() + " " + Scale[i]+ " ";
}
j += 3; //Next lower triplets (move to RH)
}
//----------------- code Ends --------------------
return NumAll.trim(); //Return trimming excess spaces if any
}
// ----------------- test sample -----------------
console.log(NumToWordsInt(67123))
console.log(NumToWordsInt(120003123))
console.log(NumToWordsInt(123999))
console.log(NumToWordsInt(789123))
console.log(NumToWordsInt(100178912))
console.log(NumToWordsInt(777))
console.log(NumToWordsInt(999999999))
console.log(NumToWordsInt(45))
I know this has been answered but I had been working on this before seeing the question. Doesn't have some small errors found in other answers. Supports up to vigintillion.
const num_text = num => {
const ones = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine"}, _tens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"], tens = {2: "twenty", 3: "thirty", 4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety"}, above_tens = ["thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion"];
var result = [];
if (/^0+$/g.test(num)) return "zero";
num = num.replace(/^0+/g, "").split(/(?=(?:...)*$)/);
for (var count = 0; count < num.length; count++){
var _result = "", _num = num[count];
_num = _num.replace(/^0+/g, "");
if (_num.length == 3){
_result += ones[_num[0]] + " hundred";
_num = _num.substring(1, 3).replace(/^0+/g, "");
if (_num.length > 0) _result += " and ";
}
if (_num.length == 1){
_result += ones[_num];
}else if (_num.length == 2){
if (_num[0] == "1"){
_result += _tens[_num[1]];
}else if (/.0/g.test(_num)){
_result += tens[_num[0]];
}else{
_result += tens[_num[0]] + " " + ones[_num[1]];
}
}
if (_result != ""){
if (num.length - count - 2 >= 0) _result += " " + above_tens[num.length - count - 2];
result.push(_result);
}
}
if (result[result.length - 1].includes("and") || result.length == 1) return result.join(", ");
return result.slice(0, result.length - 1).join(", ") + " and " + result[result.length - 1];
}
<input id="input">
<button onclick="document.getElementById('result').innerHTML = num_text(document.getElementById('input').value)">Convert</button>
<div id="result"></div>
https://stackoverflow.com/a/69243038/8784402
TypeScript Version Based on ES2022 + Fastest
Test on Typescript Playground
Hindi Version
class N2WHindi {
// "शून्य"
private static readonly zeroTo99: string[] =
'|एक|दो|तीन|चार|पाँच|छः|सात|आठ|नौ|दश|ग्यारह|बारह|तेरह|चौदह|पन्द्रह|सोलह|सत्रह|अठारह|उन्नीस|बीस|इक्कीस|बाईस|तेईस|चौबीस|पच्चीस|छब्बीस|सत्ताईस|अट्ठाईस|उनतीस|तीस|इकतीस|बत्तीस|तैंतीस|चौंतीस|पैंतीस|छत्तीस|सैंतीस|अड़तीस|उनतालीस|चालीस|इकतालीस|बयालीस|तैंतालीस|चौवालीस|पैंतालीस|छियालीस|सैंतालीस|अड़तालीस|उनचास|पचास|इक्यावन|बावन|तिरपन|चौवन|पचपन|छप्पन|सत्तावन|अट्ठावन|उनसठ|साठ|इकसठ|बासठ|तिरसठ|चौंसठ|पैंसठ|छियासठ|सड़सठ|अड़सठ|उनहत्तर|सत्तर|इकहत्तर|बहत्तर|तिहत्तर|चौहत्तर|पचहत्तर|छिहत्तर|सतहत्तर|अठहत्तर|उन्यासी|अस्सी|इक्यासी|बयासी|तिरासी|चौरासी|पचासी|छियासी|सत्तासी|अट्ठासी|नवासी|नब्बे|इक्यानबे|बानबे|तिरानबे|चौरानबे|पंचानबे|छियानबे|सत्तानबे|अट्ठानबे|निन्यान्बे'.split(
'|'
);
private static readonly place: string[] = 'हज़ार|लाख|करोड़|अरब|खरब|नील'.split('|');
public static convert(x: string): string {
let n: number = x.length;
x = n == 0 ? '00' : n == 1 || n % 2 == 0 ? '0' + x : x;
n = x.length;
let r: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n > 0) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' सौ ' + r;
}
for (let i = 0; n > 0; i++) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WHindi.place[i] + (r ? ' ' + r : '');
}
return r;
}
}
Indian English Version
class N2WIndian {
private static readonly zeroTo99: string[] = [];
private static readonly place: string[] = 'Thousand|Lakh|Crore|Arab|Kharab|Nil'.split('|');
static {
const ones: string[] =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens: string[] = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t: number = Math.floor(i / 10);
const o: number = i % 10;
N2WIndian.zeroTo99.push(t < 2 ? ones[i] : tens[t] + (o ? ' ' + ones[o] : ''));
}
}
public static convert(x: string): string {
let n: number = x.length;
x = n == 0 ? '00' : n == 1 || n % 2 == 0 ? '0' + x : x;
n = x.length;
let r = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n >= 1) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' Hundred ' + r;
}
for (let i = 0; n > 0; i++) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WIndian.place[i] + (r ? ' ' + r : '');
}
return r;
}
}
International Version
class N2WIntl {
private static readonly zeroTo999: string[] = [];
private static readonly place =
'|Thousand|Million|Billion|Trillion|Quadrillion|Quintillion|Sextillion|Septillion|Octillion|Nonillion|Decillion|Undecillion|Duodecillion|Tredecillion|Quattuordecillion|Quindecillion|Sedecillion|Septendecillion|Octodecillion|Novendecillion|Vigintillion|Unvigintillion|Duovigintillion|Tresvigintillion|Quattuorvigintillion|Quinvigintillion|Sesvigintillion|Septemvigintillion|Octovigintillion|Novemvigintillion|Trigintillion|Untrigintillion|Duotrigintillion|Trestrigintillion|Quattuortrigintillion|Quintrigintillion|Sestrigintillion|Septentrigintillion|Octotrigintillion|Noventrigintillion|Quadragintillion'.split(
'|'
);
static {
const ones =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t = Math.floor(i / 10);
const o = i % 10;
N2WIntl.zeroTo999[i] = t < 2 ? ones[i] : tens[t] + (o == 0 ? '' : ' ' + ones[o]);
}
for (let i = 100; i < 1000; i++) {
const h = Math.floor(i / 100);
const t = Math.floor(i / 10) % 10;
const o = i % 10;
const r = N2WIntl.zeroTo999[h] + ' Hundred';
N2WIntl.zeroTo999[i] = t == 0 && o == 0 ? r : r + ' ' + N2WIntl.zeroTo999[t * 10 + o];
}
}
public static convert(x: string): string {
let n = x.length;
x = n == 0 ? '000' : ((n % 3 === 1) ? '00' : (n % 3 === 2) ? '0' : '') + x;
n = x.length;
let r: string = '';
for (let i = 0; n > 0; i++) {
const v: string =
N2WIntl.zeroTo999[x.charCodeAt((n -= 3)) * 100 + x.charCodeAt(n + 1) * 10 + x.charCodeAt(n + 2) - 5328];
if (v) r = v + (i ? ' ' + N2WIntl.place[i] : '') + (r ? ' ' + r : '');
}
return r;
}
}
const test = () => {
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WHindi.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WHindi.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIndian.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WIndian.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIntl.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^126 -1 :\n' + '9'.repeat(126) + '\n' + N2WIntl.convert('9'.repeat(126)));
}
};
test();
Example to convert currency
const [r, p] = "23.54".split('.');
console.log(`${N2WHindi.convert(r)} रुपया और ${N2WHindi.convert(p)} पैसा`)
console.log(`${N2WIndian.convert(r)} Rupees and ${N2WIndian.convert(p)} Paisa`)
console.log(`${N2WIntl.convert(r)} Dollars and ${N2WIntl.convert(p)} Cents`)
I think this will help you
aTens = [ "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy","Eighty", "Ninety"];
aOnes = [ "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ];
var aUnits = "Thousand";
function convertnumbertostring(){
var num=prompt('','enter the number');
var j=6;
if(num.length<j){
var y = ConvertToWords(num);
alert(y);
}else{
alert('Enter the number of 5 letters')
}
};
function ConvertToHundreds(num)
{
var cNum, nNum;
var cWords = "";
if (num > 99) {
/* Hundreds. */
cNum = String(num);
nNum = Number(cNum.charAt(0));
cWords += aOnes[nNum] + " Hundred";
num %= 100;
if (num > 0){
cWords += " and "
}
}
if (num > 19) {
/* Tens. */
cNum = String(num);
nNum = Number(cNum.charAt(0));
cWords += aTens[nNum - 2];
num %= 10;
if (num > 0){
cWords += "-";
}
}
if (num > 0) {
/* Ones and teens. */
nNum = Math.floor(num);
cWords += aOnes[nNum];
}
return(cWords);
}
function ConvertToWords(num)
{
var cWords;
for (var i = 0; num > 0; i++) {
if (num % 1000 > 0) {
if (i != 0){
cWords = ConvertToHundreds(num) + " " + aUnits + " " + cWords;
}else{
cWords = ConvertToHundreds(num) + " ";
}
}
num = (num / 1000);
}
return(cWords);
}

Convert cents value in this INTO WORDS conversion Javascript

I have a code which convert numerical value into words. I just want to add cents in words if user inputs an amount which have a cents in value.
ex. If I have an amount of 1,000.88. The value in words will be ONE THOUSAND PESOS AND EIGHTY EIGHY CENTS ONLY.
UPDATE:
Code was edited to split the whole value and cents value. The only thing remaining is the conversion of cents into words.
FIDDLE
var NUMBER2TEXT = {
ones: ['', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN', 'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN', 'SEVENTEEN', 'EIGHTEEN', 'NINETEEN'],
tens: ['', '', 'TWENTY', 'THIRTY', 'FOURTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'],
sep: ['', ' THOUSAND ', ' MILLION ', ' BILLION ', ' TRILLION ', ' QUADRILLION ', ' QUINTILLION ', ' SEXTILLION ']
};
(function( ones, tens, sep ) {
var input = document.getElementById( 'totalamountpaid' ),
output = document.getElementById('words');
input.onkeyup = function() {
var val = this.value,
arr = [],
str = '',
i = 0;
if ( val.length === 0 ) {
output.textContent = 'No amount paid';
return;
}
val = val.replace(/,/g,'');
if ( isNaN( val ) ) {
output.textContent = 'Invalid input.';
return;
}
val = val.toString();
var valArray = val.split('\.', 2); //splits val into two seperate integers, whole numbers and decimals, in an array.
val = valArray[0]; //this is the whole number
var val2 = valArray[1]; //this should be the decimals
if(val2 != null && val2 != ''){
//convert the decimals here
var str2 = 'AND TWENTY CENTS';
}else{
var str2 = '';
}
while ( val ) {
arr.push( val % 1000 );
val = parseInt( val / 1000, 10 );
}
while ( arr.length ) {
str = (function( a ) {
var x = Math.floor( a / 100 ),
y = Math.floor( a / 10 ) % 10,
z = a % 10;
return ( x > 0 ? ones[x] + ' HUNDRED ' : '' ) +
( y >= 2 ? tens[y] + ' ' + ones[z] : ones[10*y + z] );
})( arr.shift() ) + sep[i++] + str;
}
output.textContent = str + ' ' + str2 + ' PESOS ONLY';
};
})( NUMBER2TEXT.ones, NUMBER2TEXT.tens, NUMBER2TEXT.sep );
Sorry for the wait, for some reason this line was attacking my code.
val = parseInt( val.replace(/,/g,''), 10 );
I changed it to:
val = val.replace(/,/g,'');
which seems to have the same functionality while allowing me to do my thing. Here is the code. I use regexes to test for a period in val (the if statement), and then to split val into things before and after a period. The 2 in the split function should only allow for 2 strings to come out of it, meaning 10.20 would become '10' and '20' where 1.2.3 would become '1' and '2', and throw away 3. Arrays start at 0, so valArray[0] is the first string in the array, and valArray[1] is the second one.
val = val.toString();
var valArray = val.split('\.', 2); //splits val into two seperate integers, whole numbers and decimals, in an array.
val = valArray[0]; //this is the whole number
var val2 = valArray[1]; //this should be the decimals
if(val2 != null && val2 != ''){
//convert the decimals here
var str2 = 'TWENTY CENTS';
}
else{
var str2 = '';
}
UPDATE: FIDDLE
Here is a complete version using dollars and cents
const num2text = {
ones: ['', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN', 'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN', 'SEVENTEEN', 'EIGHTEEN', 'NINETEEN'],
tens: ['', '', 'TWENTY', 'THIRTY', 'FOURTH', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'],
sep: ['', ' THOUSAND ', ' MILLION ', ' BILLION ', ' TRILLION ', ' QUADRILLION ', ' QUINTILLION ', ' SEXTILLION ']
};
const convert = function(val) {
if (val.length === 0) {
return '';
}
val = val.replace(/,/g, '');
if (isNaN(val)) {
return 'Invalid input.';
}
let [val1, val2] = val.split(".")
let str2 = "";
if (val2 != null && val2 != '') {
//convert the decimals here
var digits = (val2+"0").slice(0,2).split("");
str2 = num2text.tens[+digits[0]] + " " + num2text.ones[+digits[1]]
}
let arr = [];
while (val1) {
arr.push(val1 % 1000);
val1 = parseInt(val1 / 1000, 10);
}
let i = 0;
let str = "";
while (arr.length) {
str = (function(a) {
var x = Math.floor(a / 100),
y = Math.floor(a / 10) % 10,
z = a % 10;
return (x > 0 ? num2text.ones[x] + ' HUNDRED ' : '') +
(y >= 2 ? num2text.tens[y] + ' ' + num2text.ones[z] : num2text.ones[10 * y + z]);
})(arr.shift()) + num2text.sep[i++] + str;
}
return str +
' DOLLARS ' +
(str2 ? ' AND ' + str2 + ' CENTS' : '') +
' ONLY';
};
window.addEventListener("load", function() {
document.getElementById("totalamountpaid").addEventListener("input", function() {
document.getElementById("words").innerHTML = convert(this.value)
});
});
<input id="totalamountpaid" placeholder="input amount" />
<br><br>
<label id="words"><label>

JavaScript numbers to Words

I'm trying to convert numbers into english words, for example 1234 would become: "one thousand two hundred thirty four".
My Tactic goes like this:
Separate the digits to three and put them on Array (finlOutPut), from right to left.
Convert each group (each cell in the finlOutPut array) of three digits to a word (this what the triConvert function does). If all the three digits are zero convert them to "dontAddBigSuffix"
From Right to left, add thousand, million, billion, etc. If the finlOutPut cell equals "dontAddBigSufix" (because it was only zeroes), don't add the word and set the cell to " " (nothing).
It seems to work pretty well, but I've got some problems with numbers like 190000009, converted to: "one hundred ninety million". Somehow it "forgets" the last numbers when there are a few zeros.
What did I do wrong? Where is the bug? Why does it not work perfectly?
function update(){
var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');
var output = '';
var numString = document.getElementById('number').value;
var finlOutPut = new Array();
if (numString == '0') {
document.getElementById('container').innerHTML = 'Zero';
return;
}
if (numString == 0) {
document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
return;
}
var i = numString.length;
i = i - 1;
//cut the number to grups of three digits and add them to the Arry
while (numString.length > 3) {
var triDig = new Array(3);
triDig[2] = numString.charAt(numString.length - 1);
triDig[1] = numString.charAt(numString.length - 2);
triDig[0] = numString.charAt(numString.length - 3);
var varToAdd = triDig[0] + triDig[1] + triDig[2];
finlOutPut.push(varToAdd);
i--;
numString = numString.substring(0, numString.length - 3);
}
finlOutPut.push(numString);
finlOutPut.reverse();
//conver each grup of three digits to english word
//if all digits are zero the triConvert
//function return the string "dontAddBigSufix"
for (j = 0; j < finlOutPut.length; j++) {
finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
}
var bigScalCntr = 0; //this int mark the million billion trillion... Arry
for (b = finlOutPut.length - 1; b >= 0; b--) {
if (finlOutPut[b] != "dontAddBigSufix") {
finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
bigScalCntr++;
}
else {
//replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
finlOutPut[b] = ' ';
bigScalCntr++; //advance the counter
}
}
//convert The output Arry to , more printable string
for(n = 0; n<finlOutPut.length; n++){
output +=finlOutPut[n];
}
document.getElementById('container').innerHTML = output;//print the output
}
//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
var hundred = ' hundred';
var output = '';
var numString = num.toString();
if (num == 0) {
return 'dontAddBigSufix';
}
//the case of 10, 11, 12 ,13, .... 19
if (num < 20) {
output = ones[num];
return output;
}
//100 and more
if (numString.length == 3) {
output = ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output += ones[parseInt(numString.charAt(2))];
return output;
}
output += tens[parseInt(numString.charAt(0))];
output += ones[parseInt(numString.charAt(1))];
return output;
}
<input type="text"
id="number"
size="70"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"/>
<br/>
<div id="container">Here The Numbers Printed</div>
JavaScript is parsing the group of 3 numbers as an octal number when there's a leading zero digit. When the group of three digits is all zeros, the result is the same whether the base is octal or decimal.
But when you give JavaScript '009' (or '008'), that's an invalid octal number, so you get zero back.
If you had gone through the whole set of numbers from 190,000,001 to 190,000,010 you'd hav seen JavaScript skip '...,008' and '...,009' but emit 'eight' for '...,010'. That's the 'Eureka!' moment.
Change:
for (j = 0; j < finlOutPut.length; j++) {
finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
}
to
for (j = 0; j < finlOutPut.length; j++) {
finlOutPut[j] = triConvert(parseInt(finlOutPut[j],10));
}
Code also kept on adding commas after every non-zero group, so I played with it and found the right spot to add the comma.
Old:
for (b = finlOutPut.length - 1; b >= 0; b--) {
if (finlOutPut[b] != "dontAddBigSufix") {
finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
bigScalCntr++;
}
else {
//replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
finlOutPut[b] = ' ';
bigScalCntr++; //advance the counter
}
}
//convert The output Arry to , more printable string
for(n = 0; n<finlOutPut.length; n++){
output +=finlOutPut[n];
}
New:
for (b = finlOutPut.length - 1; b >= 0; b--) {
if (finlOutPut[b] != "dontAddBigSufix") {
finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr]; // <<<
bigScalCntr++;
}
else {
//replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
finlOutPut[b] = ' ';
bigScalCntr++; //advance the counter
}
}
//convert The output Arry to , more printable string
var nonzero = false; // <<<
for(n = 0; n<finlOutPut.length; n++){
if (finlOutPut[n] != ' ') { // <<<
if (nonzero) output += ' , '; // <<<
nonzero = true; // <<<
} // <<<
output +=finlOutPut[n];
}
Your problem is already solved but I am posting another way of doing it just for reference.
The code was written to be tested on node.js, but the functions should work fine when called within the browser. Also, this only handles the range [0,1000000], but can be easily adapted for bigger ranges.
// actual conversion code starts here
var ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
var teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
function convert_millions(num) {
if (num >= 1000000) {
return convert_millions(Math.floor(num / 1000000)) + " million " + convert_thousands(num % 1000000);
} else {
return convert_thousands(num);
}
}
function convert_thousands(num) {
if (num >= 1000) {
return convert_hundreds(Math.floor(num / 1000)) + " thousand " + convert_hundreds(num % 1000);
} else {
return convert_hundreds(num);
}
}
function convert_hundreds(num) {
if (num > 99) {
return ones[Math.floor(num / 100)] + " hundred " + convert_tens(num % 100);
} else {
return convert_tens(num);
}
}
function convert_tens(num) {
if (num < 10) return ones[num];
else if (num >= 10 && num < 20) return teens[num - 10];
else {
return tens[Math.floor(num / 10)] + " " + ones[num % 10];
}
}
function convert(num) {
if (num == 0) return "zero";
else return convert_millions(num);
}
//end of conversion code
//testing code begins here
function main() {
var cases = [0, 1, 2, 7, 10, 11, 12, 13, 15, 19, 20, 21, 25, 29, 30, 35, 50, 55, 69, 70, 99, 100, 101, 119, 510, 900, 1000, 5001, 5019, 5555, 10000, 11000, 100000, 199001, 1000000, 1111111, 190000009];
for (var i = 0; i < cases.length; i++) {
console.log(cases[i] + ": " + convert(cases[i]));
}
}
main();
I know this problem had solved 3 years ago. I am posting this SPECIALLY FOR INDIAN DEVELOPERS
After spending some time in googling and playing with others code i made a quick fix and reusable function works well for numbers upto 99,99,99,999. use : number2text(1234.56); will return ONE THOUSAND TWO HUNDRED AND THIRTY-FOUR RUPEE AND FIFTY-SIX PAISE ONLY . enjoy !
function number2text(value) {
var fraction = Math.round(frac(value)*100);
var f_text = "";
if(fraction > 0) {
f_text = "AND "+convert_number(fraction)+" PAISE";
}
return convert_number(value)+" RUPEE "+f_text+" ONLY";
}
function frac(f) {
return f % 1;
}
function convert_number(number)
{
if ((number < 0) || (number > 999999999))
{
return "NUMBER OUT OF RANGE!";
}
var Gn = Math.floor(number / 10000000); /* Crore */
number -= Gn * 10000000;
var kn = Math.floor(number / 100000); /* lakhs */
number -= kn * 100000;
var Hn = Math.floor(number / 1000); /* thousand */
number -= Hn * 1000;
var Dn = Math.floor(number / 100); /* Tens (deca) */
number = number % 100; /* Ones */
var tn= Math.floor(number / 10);
var one=Math.floor(number % 10);
var res = "";
if (Gn>0)
{
res += (convert_number(Gn) + " CRORE");
}
if (kn>0)
{
res += (((res=="") ? "" : " ") +
convert_number(kn) + " LAKH");
}
if (Hn>0)
{
res += (((res=="") ? "" : " ") +
convert_number(Hn) + " THOUSAND");
}
if (Dn)
{
res += (((res=="") ? "" : " ") +
convert_number(Dn) + " HUNDRED");
}
var ones = Array("", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX","SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN","FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN","NINETEEN");
var tens = Array("", "", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY","SEVENTY", "EIGHTY", "NINETY");
if (tn>0 || one>0)
{
if (!(res==""))
{
res += " AND ";
}
if (tn < 2)
{
res += ones[tn * 10 + one];
}
else
{
res += tens[tn];
if (one>0)
{
res += ("-" + ones[one]);
}
}
}
if (res=="")
{
res = "zero";
}
return res;
}
Indian Version
Updated version of #jasonhao 's answer for Indian currency
function intToEnglish(number) {
var NS = [
{ value: 10000000, str: "Crore" },
{ value: 100000, str: "Lakh" },
{ value: 1000, str: "Thousand" },
{ value: 100, str: "Hundred" },
{ value: 90, str: "Ninety" },
{ value: 80, str: "Eighty" },
{ value: 70, str: "Seventy" },
{ value: 60, str: "Sixty" },
{ value: 50, str: "Fifty" },
{ value: 40, str: "Forty" },
{ value: 30, str: "Thirty" },
{ value: 20, str: "Twenty" },
{ value: 19, str: "Nineteen" },
{ value: 18, str: "Eighteen" },
{ value: 17, str: "Seventeen" },
{ value: 16, str: "Sixteen" },
{ value: 15, str: "Fifteen" },
{ value: 14, str: "Fourteen" },
{ value: 13, str: "Thirteen" },
{ value: 12, str: "Twelve" },
{ value: 11, str: "Eleven" },
{ value: 10, str: "Ten" },
{ value: 9, str: "Nine" },
{ value: 8, str: "Eight" },
{ value: 7, str: "Seven" },
{ value: 6, str: "Six" },
{ value: 5, str: "Five" },
{ value: 4, str: "Four" },
{ value: 3, str: "Three" },
{ value: 2, str: "Two" },
{ value: 1, str: "One" }
];
var result = '';
for (var n of NS) {
if (number >= n.value) {
if (number <= 99) {
result += n.str;
number -= n.value;
if (number > 0) result += ' ';
} else {
var t = Math.floor(number / n.value);
// console.log(t);
var d = number % n.value;
if (d > 0) {
return intToEnglish(t) + ' ' + n.str + ' ' + intToEnglish(d);
} else {
return intToEnglish(t) + ' ' + n.str;
}
}
}
}
return result;
}
console.log(intToEnglish(99))
console.log(intToEnglish(991199))
console.log(intToEnglish(123456799))
There are JS library for en_US and cs_CZ.
You can use it standalone or as Node module.
Numbers2Words
Here, I wrote an alternative solution:
1) The object containing the string constants:
var NUMBER2TEXT = {
ones: ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
tens: ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'],
sep: ['', ' thousand ', ' million ', ' billion ', ' trillion ', ' quadrillion ', ' quintillion ', ' sextillion ']
};
2) The actual code:
(function( ones, tens, sep ) {
var input = document.getElementById( 'input' ),
output = document.getElementById( 'output' );
input.onkeyup = function() {
var val = this.value,
arr = [],
str = '',
i = 0;
if ( val.length === 0 ) {
output.textContent = 'Please type a number into the text-box.';
return;
}
val = parseInt( val, 10 );
if ( isNaN( val ) ) {
output.textContent = 'Invalid input.';
return;
}
while ( val ) {
arr.push( val % 1000 );
val = parseInt( val / 1000, 10 );
}
while ( arr.length ) {
str = (function( a ) {
var x = Math.floor( a / 100 ),
y = Math.floor( a / 10 ) % 10,
z = a % 10;
return ( x > 0 ? ones[x] + ' hundred ' : '' ) +
( y >= 2 ? tens[y] + ' ' + ones[z] : ones[10*y + z] );
})( arr.shift() ) + sep[i++] + str;
}
output.textContent = str;
};
})( NUMBER2TEXT.ones, NUMBER2TEXT.tens, NUMBER2TEXT.sep );
Live demo: http://jsfiddle.net/j5kdG/
A version with a compact object - for numbers from zero to 999.
function wordify(n) {
var word = [],
numbers = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', t3: 'Thir', t5: 'Fif', t8: 'Eigh', 20: 'Twenty' },
hundreds = 0 | (n % 1000) / 100,
tens = 0 | (n % 100) / 10,
ones = n % 10,
part;
if (n === 0) return 'Zero';
if (hundreds) word.push(numbers[hundreds] + ' Hundred');
if (tens === 0) {
word.push(numbers[ones]);
} else if (tens === 1) {
word.push(numbers['1' + ones] || (numbers['t' + ones] || numbers[ones]) + 'teen');
} else {
part = numbers[tens + '0'] || (numbers['t' + tens] || numbers[tens]) + 'ty';
word.push(numbers[ones] ? part + '-' + numbers[ones] : part);
}
return word.join(' ');
}
var i,
output = document.getElementById('out');
for (i = 0; i < 1e3; i++) output.innerHTML += wordify(i) + '\n';
<pre id="out"></pre>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
var th = ['', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion'];
var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function update(){
var numString = document.getElementById('number').value;
if (numString == '0') {
document.getElementById('container').innerHTML = 'Zero';
return;
}
if (numString == 0) {
document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
return;
}
var output = toWords(numString);
//print the output
document.getElementById('container').innerHTML = output;
}
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
} else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
} else if (n[i] != 0) {
str += dg[n[i]] + ' ';
if ((x - i) % 3 == 0) str += 'hundred ';
sk = 1;
}
if ((x - i) % 3 == 1) {
if (sk) str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
return str.replace(/\s+/g, ' ');
}
</script>
</head>
<body>
<input type="text"
id="number"
size="70"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"/>
<br/>
<div id="container">Here The Numbers Printed</div>
</body>
</html>
Try this,convert number to words
function convert(number) {
if (number < 0) {
console.log("Number Must be greater than zero = " + number);
return "";
}
if (number > 100000000000000000000) {
console.log("Number is out of range = " + number);
return "";
}
if (!is_numeric(number)) {
console.log("Not a number = " + number);
return "";
}
var quintillion = Math.floor(number / 1000000000000000000); /* quintillion */
number -= quintillion * 1000000000000000000;
var quar = Math.floor(number / 1000000000000000); /* quadrillion */
number -= quar * 1000000000000000;
var trin = Math.floor(number / 1000000000000); /* trillion */
number -= trin * 1000000000000;
var Gn = Math.floor(number / 1000000000); /* billion */
number -= Gn * 1000000000;
var million = Math.floor(number / 1000000); /* million */
number -= million * 1000000;
var Hn = Math.floor(number / 1000); /* thousand */
number -= Hn * 1000;
var Dn = Math.floor(number / 100); /* Tens (deca) */
number = number % 100; /* Ones */
var tn = Math.floor(number / 10);
var one = Math.floor(number % 10);
var res = "";
if (quintillion > 0) {
res += (convert_number(quintillion) + " quintillion");
}
if (quar > 0) {
res += (convert_number(quar) + " quadrillion");
}
if (trin > 0) {
res += (convert_number(trin) + " trillion");
}
if (Gn > 0) {
res += (convert_number(Gn) + " billion");
}
if (million > 0) {
res += (((res == "") ? "" : " ") + convert_number(million) + " million");
}
if (Hn > 0) {
res += (((res == "") ? "" : " ") + convert_number(Hn) + " Thousand");
}
if (Dn) {
res += (((res == "") ? "" : " ") + convert_number(Dn) + " hundred");
}
var ones = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", "Nineteen");
var tens = Array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eigthy", "Ninety");
if (tn > 0 || one > 0) {
if (!(res == "")) {
res += " and ";
}
if (tn < 2) {
res += ones[tn * 10 + one];
} else {
res += tens[tn];
if (one > 0) {
res += ("-" + ones[one]);
}
}
}
if (res == "") {
console.log("Empty = " + number);
res = "";
}
return res;
}
function is_numeric(mixed_var) {
return (typeof mixed_var === 'number' || typeof mixed_var === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}
function intToEnglish(number){
var NS = [
{value: 1000000000000000000000, str: "sextillion"},
{value: 1000000000000000000, str: "quintillion"},
{value: 1000000000000000, str: "quadrillion"},
{value: 1000000000000, str: "trillion"},
{value: 1000000000, str: "billion"},
{value: 1000000, str: "million"},
{value: 1000, str: "thousand"},
{value: 100, str: "hundred"},
{value: 90, str: "ninety"},
{value: 80, str: "eighty"},
{value: 70, str: "seventy"},
{value: 60, str: "sixty"},
{value: 50, str: "fifty"},
{value: 40, str: "forty"},
{value: 30, str: "thirty"},
{value: 20, str: "twenty"},
{value: 19, str: "nineteen"},
{value: 18, str: "eighteen"},
{value: 17, str: "seventeen"},
{value: 16, str: "sixteen"},
{value: 15, str: "fifteen"},
{value: 14, str: "fourteen"},
{value: 13, str: "thirteen"},
{value: 12, str: "twelve"},
{value: 11, str: "eleven"},
{value: 10, str: "ten"},
{value: 9, str: "nine"},
{value: 8, str: "eight"},
{value: 7, str: "seven"},
{value: 6, str: "six"},
{value: 5, str: "five"},
{value: 4, str: "four"},
{value: 3, str: "three"},
{value: 2, str: "two"},
{value: 1, str: "one"}
];
var result = '';
for (var n of NS) {
if(number>=n.value){
if(number<=20){
result += n.str;
number -= n.value;
if(number>0) result += ' ';
}else{
var t = Math.floor(number / n.value);
var d = number % n.value;
if(d>0){
return intToEnglish(t) + ' ' + n.str +' ' + intToEnglish(d);
}else{
return intToEnglish(t) + ' ' + n.str;
}
}
}
}
return result;
}
This is a simple ES6+ number to words function. You can simply add 'illions' array to extend digits. American English version.
(no 'and' before the end)
// generic number to words
let digits = ['','one','two','three','four', 'five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
let ties = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
let illions = ['', 'thousand', 'million', 'billion', 'trillion'].reverse()
let join = (a, s) => a.filter(v => v).join(s || ' ')
let tens = s =>
digits[s] ||
join([ties[s[0]], digits[s[1]]], '-') // 21 -> twenty-one
let hundreds = s =>
join(
(s[0] !== '0' ? [digits[s[0]], 'hundred'] : [])
.concat( tens(s.substr(1,2)) ) )
let re = '^' + '(\\d{3})'.repeat(illions.length) + '$'
let numberToWords = n =>
// to filter non number or '', null, undefined, false, NaN
isNaN(Number(n)) || !n && n !== 0
? 'not a number'
: Number(n) === 0
? 'zero'
: Number(n) >= 10 ** (illions.length * 3)
? 'too big'
: String(n)
.padStart(illions.length * 3, '0')
.match(new RegExp(re))
.slice(1, illions.length + 1)
.reduce( (a, v, i) => v === '000' ? a : join([a, hundreds(v), illions[i]]), '')
// just for this question.
let update = () => {
let value = document.getElementById('number').value
document.getElementById('container').innerHTML = numberToWords(value)
}
Here's a solution that will handle any integer value that fit's in a string. I've defined number scales up to "decillion", so this solution should be accurate up to 999 decillion. After which you get things like "one thousand decillion" and so on.
JavaScript numbers start to fail around "999999999999999" so the convert function works with strings of numbers only.
Examples:
convert("365");
//=> "three hundred sixty-five"
convert("10000000000000000000000000000230001010109");
//=> "ten thousand decillion two hundred thirty billion one million ten thousand one hundred nine"
Code:
var lt20 = ["", "one", "two", "three", "four", "five", "six", "seven","eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ],
tens = ["", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eightty", "ninety" ],
scales = ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion" ],
max = scales.length * 3;
function convert(val) {
var len;
// special cases
if (val[0] === "-") { return "negative " + convert(val.slice(1)); }
if (val === "0") { return "zero"; }
val = trim_zeros(val);
len = val.length;
// general cases
if (len < max) { return convert_lt_max(val); }
if (len >= max) { return convert_max(val); }
}
function convert_max(val) {
return split_rl(val, max)
.map(function (val, i, arr) {
if (i < arr.length - 1) {
return convert_lt_max(val) + " " + scales.slice(-1);
}
return convert_lt_max(val);
})
.join(" ");
}
function convert_lt_max(val) {
var l = val.length;
if (l < 4) {
return convert_lt1000(val).trim();
} else {
return split_rl(val, 3)
.map(convert_lt1000)
.reverse()
.map(with_scale)
.reverse()
.join(" ")
.trim();
}
}
function convert_lt1000(val) {
var rem, l;
val = trim_zeros(val);
l = val.length;
if (l === 0) { return ""; }
if (l < 3) { return convert_lt100(val); }
if (l === 3) { //less than 1000
rem = val.slice(1);
if (rem) {
return lt20[val[0]] + " hundred " + convert_lt1000(rem);
} else {
return lt20[val[0]] + " hundred";
}
}
}
function convert_lt100(val) {
if (is_lt20(val)) { // less than 20
return lt20[val];
} else if (val[1] === "0") {
return tens[val[0]];
} else {
return tens[val[0]] + "-" + lt20[val[1]];
}
}
function split_rl(str, n) {
// takes a string 'str' and an integer 'n'. Splits 'str' into
// groups of 'n' chars and returns the result as an array. Works
// from right to left.
if (str) {
return Array.prototype.concat
.apply(split_rl(str.slice(0, (-n)), n), [str.slice(-n)]);
} else {
return [];
}
}
function with_scale(str, i) {
var scale;
if (str && i > (-1)) {
scale = scales[i];
if (scale !== undefined) {
return str.trim() + " " + scale;
} else {
return convert(str.trim());
}
} else {
return "";
}
}
function trim_zeros(val) {
return val.replace(/^0*/, "");
}
function is_lt20(val) {
return parseInt(val, 10) < 20;
}
I've modified the posting from Šime Vidas - http://jsfiddle.net/j5kdG/
To include dollars, cents, commas and "and" in the appropriate places.
There's an optional ending if it requires "zero cents" or no mention of cents if 0.
This function structure did my head in a bit but I learned heaps. Thanks Sime.
Someone might find a better way of processing this.
Code:
var str='';
var str2='';
var str3 =[];
function convertNum(inp,end){
str2='';
str3 = [];
var NUMBER2TEXT = {
ones: ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
tens: ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'],
sep: ['', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion', ' sextillion']
};
(function( ones, tens, sep ) {
var vals = inp.split("."),val,pos,postsep=' ';
for (p in vals){
val = vals[p], arr = [], str = '', i = 0;
if ( val.length === 0 ) {return 'No value';}
val = parseInt( (p==1 && val.length===1 )?val*10:val, 10 );
if ( isNaN( val ) || p>=2) {return 'Invalid value'; }
while ( val ) {
arr.push( val % 1000 );
val = parseInt( val / 1000, 10 );
}
pos = arr.length;
function trimx (strx) {
return strx.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function seps(sepi,i){
var s = str3.length
if (str3[s-1][0]){
if (str3[s-2][1] === str3[s-1][0]){
str = str.replace(str3[s-2][1],'')
}
}
var temp = str.split(sep[i-2]);
if (temp.length > 1){
if (trimx(temp[0]) ==='' && temp[1].length > 1 ){
str = temp[1];
}
}
return sepi + str ;
}
while ( arr.length ) {
str = (function( a ) {
var x = Math.floor( a / 100 ),
y = Math.floor( a / 10 ) % 10,
z = a % 10;
postsep = (arr.length != 0)?', ' : ' ' ;
if ((x+y+z) === 0){
postsep = ' '
}else{
if (arr.length == pos-1 && x===0 && pos > 1 ){
postsep = ' and '
}
}
str3.push([trimx(str)+"",trimx(sep[i])+""]);
return (postsep)+( x > 0 ? ones[x] + ' hundred ' + (( x == 0 && y >= 0 || z >0 )?' and ':' ') : ' ' ) +
( y >= 2 ? tens[y] + ((z===0)?' ':'-') + ones[z] : ones[10*y + z] );
})( arr.shift() ) +seps( sep[i++] ,i ) ;
}
if (p==0){ str2 += str + ' dollars'}
if (p==1 && !end){str2 += (str!='')?' and '+ str + ' cents':'' }
if (p==1 && end ){str2 += ' and ' + ((str==='')?'zero':str) + ' cents '}
}
})( NUMBER2TEXT.ones , NUMBER2TEXT.tens , NUMBER2TEXT.sep );
this is the solution for french language
it's a fork for #gandil response
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
var th = ['', ' mille', ' millions', ' milliards', ' billions', ' mille-billions', ' trillion'];
var dg = ['zéro', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf'];
var tn = ['dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf'];
var tw = ['vingt', 'trente', 'quarante', 'cinquante', 'soixante', 'soixante-dix', 'quatre-vingts', 'quatre-vingt-dix'];
function update(){
var numString = document.getElementById('number').value;
if (numString == '0') {
document.getElementById('container').innerHTML = 'Zéro';
return;
}
if (numString == 0) {
document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
return;
}
var output = toWords(numString);
//output.split('un mille').join('msille ');
//output.replace('un cent', 'cent ');
//print the output
//if(output.length == 4){output = 'sss';}
document.getElementById('container').innerHTML = output;
}
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
} else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
} else if (n[i] != 0) {
str += dg[n[i]] + ' ';
//if((dg[n[i]] == 'un') && ((x - i) / 3 == 1)){str = 'cent ';}
if ((x - i) % 3 == 0) {str += 'cent ';}
sk = 1;
}
if ((x - i) % 3 == 1) {
//test
if((x - i - 1) / 3 == 1){
var long = str.length;
subs = str.substr(long-3);
if(subs.search("un")!= -1){
//str += 'OK';
str = str.substr(0, long-4);
}
}
//test
if (sk) str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
//if(str.length == 4){}
str.replace(/\s+/g, ' ');
return str.split('un cent').join('cent ');
//return str.replace('un cent', 'cent ');
}
</script>
</head>
<body>
<input type="text"
id="number"
size="70"
onkeyup="update();"
/*this code prevent non numeric letters*/
onkeydown="return (event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"/>
<br/>
<div id="container">Here The Numbers Printed</div>
</body>
</html>
i hope it will help
A little code snippet for INDONESIAN DEVELOPER to translate numeric value into verbal spelling (minimized by hand, only 576 bytes, requires ES6+)...
const terbilang=(x,nol='---',min='minus')=>{const S=['','satu','dua','tiga','empat','lima','enam','tujuh','delapan','sembilan'],K=['','ribu','juta','miliar','triliun','kuadriliun'],s=[];if(!x)return nol;if(x<0){if(min)s=[min];x=-x}for(let k=0;x;k++){let g=x%1e3;if(g===1&&k===1)s.unshift('seribu');else{let u=g>99?[(g>199?S[g/100|0]+' ':'se')+'ratus']:[];if(g%=100){if(g>9&&g<20)u.push(g<11?'sepuluh':(g<12?'se':S[g%10]+' ')+'belas');else{if(g>19)u.push(S[g/10|0]+' puluh');if(g%=10)u.push(S[g])}}k&&u.push(K[k]);s.unshift(u.join(' '))}x=Math.floor(x/1e3)}return s.join(' ')};
function toWords(...x) {
let space = /\s/g;
let digit = /\d/g;
let trio = /.../g;
let unit = ' one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'.split(space);
let ten = ' twenty thirty forty fifty sixty seventy eighty ninety'.split(space);
let scale = ' thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion'.split(space);
let d = digit.test(x) ? String(x).match(digit) : ['0'];
while (d.length % 3) d.unshift('0');
d = d.join('').match(trio).map(function verbose(string) {
let number = Number(string);
return (number < 20) ?
unit[number] :
(number < 100) ?
[ten[Number(string.slice(0, -1))], verbose(string.slice(-1))].filter(Boolean).join('-') :
[verbose(string.slice(0, -2)), 'hundred', verbose(string.slice(-2))].filter(Boolean).join(' ');
}).reverse().map(function(v, i, a) {
return v ? [v, scale[i]].filter(Boolean).join(' ') : v;
}).reverse().filter(Boolean).join(', ');
return d ? d : 'zero';
}
toWords('14,702,000,583,690,010');
// 'fourteen quadrillion, seven hundred two trillion, five hundred eighty-three million, six hundred ninety thousand, ten'
Update Feb 2022
A simple and short Javascript function to do the conversion of numbers (integers) to words in English (US System) and give the correct results is included below using a forEach() loop with the String Triplets Array method.
The number is first converted into a string triplet array using:
num= ("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
The string array is then easily decoded into numbers.
For example, the number 1234567 is converted into an array of string triplets:
[ '001', '234', '567' ]
Each element is then scanned from left to right by the forEach() loop.
This is a far better solution than using a for loop that I had proposed 2 years ago.
You can increase the scale array above the 'Quadrillion' if you prefer.
If the input number is too large, then pass it as a "string".
Test cases are also included.
/********************************************************
* #function : numToWords(number)
* #purpose : Converts Unsigned Integers to Words
* #version : 1.50
* #author : Mohsen Alyafei
* #licence : MIT
* #date : 26 Feb 2022
* #param : {number} [integer numeric or string]
* #returns : {string} The wordified number string
********************************************************/
//==============================================================
function numToWords(num = 0) {
if (num == 0) return "Zero";
num= ("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
let out="",
T10s=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
T20s=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],
sclT=["","Thousand","Million","Billion","Trillion","Quadrillion"];
return num.forEach((n,i) => {
if (+n) {
let hund=+n[0], ten=+n.substring(1), scl=sclT[num.length-i-1];
out+=(out?" ":"")+(hund?T10s[hund]+" Hundred":"")+(hund && ten?" ":"")+(ten<20?T10s[ten]:T20s[+n[1]]+(+n[2]?"-":"")+T10s[+n[2]]);
out+=(out && scl?" ":"")+scl;
}}),out;
}
//==============================================================
//=========================================
// Test Code
//=========================================
var r=0; // test tracker
r |= test(0,"Zero");
r |= test(5,"Five");
r |= test(10,"Ten");
r |= test(19,"Nineteen");
r |= test(33,"Thirty-Three");
r |= test(100,"One Hundred");
r |= test(111,"One Hundred Eleven");
r |= test(890,"Eight Hundred Ninety");
r |= test(1234,"One Thousand Two Hundred Thirty-Four");
r |= test(12345,"Twelve Thousand Three Hundred Forty-Five");
r |= test(123456,"One Hundred Twenty-Three Thousand Four Hundred Fifty-Six");
r |= test(1234567,"One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven");
r |= test(12345678,"Twelve Million Three Hundred Forty-Five Thousand Six Hundred Seventy-Eight");
r |= test(123456789,"One Hundred Twenty-Three Million Four Hundred Fifty-Six Thousand Seven Hundred Eighty-Nine");
r |= test(1234567890,"One Billion Two Hundred Thirty-Four Million Five Hundred Sixty-Seven Thousand Eight Hundred Ninety");
r |= test(1001,"One Thousand One");
r |= test(10001,"Ten Thousand One");
r |= test(100001,"One Hundred Thousand One");
r |= test(1000001,"One Million One");
r |= test(10000001,"Ten Million One");
r |= test(100000001,"One Hundred Million One");
r |= test(12012,"Twelve Thousand Twelve");
r |= test(120012,"One Hundred Twenty Thousand Twelve");
r |= test(1200012,"One Million Two Hundred Thousand Twelve");
r |= test(12000012,"Twelve Million Twelve");
r |= test(120000012,"One Hundred Twenty Million Twelve");
r |= test(75075,"Seventy-Five Thousand Seventy-Five");
r |= test(750075,"Seven Hundred Fifty Thousand Seventy-Five");
r |= test(7500075,"Seven Million Five Hundred Thousand Seventy-Five");
r |= test(75000075,"Seventy-Five Million Seventy-Five");
r |= test(750000075,"Seven Hundred Fifty Million Seventy-Five");
r |= test(1000,"One Thousand");
r |= test(1000000,"One Million");
r |= test(1000000000,"One Billion");
r |= test(1000000000000,"One Trillion");
r |= test("1000000000000000","One Quadrillion");
if (r==0) console.log("All Test Cases Passed.");
function test(n,should) {
let result = numToWords(n);
if (result !== should) {console.log(`${n} Output : ${result}\n${n} Should be: ${should}`);return 1;}
}
I would like to point out that the original logic fails for values between x11-x19, where x >= 1. For example, 118 returns "one hundred eight". This is because these numbers are processed by the following code in triConvert():
//100 and more
if (numString.length == 3) {
output = ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output += ones[parseInt(numString.charAt(2))];
return output;
}
here, the character representing the tens digit is used to index the tens[] array, which has an empty string at index [1], so 118 become 108 in effect.
It might be better to deal with the hundreds (if any first), then run the ones and tens through the same logic. Instead of:
//the case of 10, 11, 12 ,13, .... 19
if (num < 20) {
output = ones[num];
return output;
}
//100 and more
if (numString.length == 3) {
output = ones[parseInt(numString.charAt(0))] + hundred;
output += tens[parseInt(numString.charAt(1))];
output += ones[parseInt(numString.charAt(2))];
return output;
}
output += tens[parseInt(numString.charAt(0))];
output += ones[parseInt(numString.charAt(1))];
return output;
I would suggest:
// 100 and more
if ( numString.length == 3 )
{
output = hundreds[ parseInt( numString.charAt(0) ) ] + hundred ;
num = num % 100 ;
numString = num.toString() ;
}
if ( num < 20 )
{
output += ones[num] ;
}
else
{ // 20-99
output += tens[ parseInt( numString.charAt(0) ) ] ;
output += '-' + ones[ parseInt( numString.charAt(1) ) ] ;
}
return output;
It seems to me that the suggested code is both shorter and clearer, but I might be biased ;-)
Source: http://javascript.about.com/library/bltoword.htm
Smallest script that I found:
<script type="text/javascript" src="toword.js">
var words = toWords(12345);
console.log(words);
</script>
Enjoy!
I tried Muhammad's solution, but had some issues and wanted to use decimals so I made some changes and converted to coffeescript and angular. Please bear in mind that js and coffeescript are not my strong suits, so use with care.
$scope.convert = (number, upper=0) ->
number = +number
# console.log "inside convert and the number is: " + number
if number < 0
# console.log 'Number Must be greater than zero = ' + number
return ''
if number > 100000000000000000000
# console.log 'Number is out of range = ' + number
return ''
if isNaN(number)
console.log("NOT A NUMBER")
alert("Not a number = ")
return ''
else
console.log "at line 88 number is: " + number
quintillion = Math.floor(number / 1000000000000000000)
### quintillion ###
number -= quintillion * 1000000000000000000
quar = Math.floor(number / 1000000000000000)
# console.log "at line 94 number is: " + number
### quadrillion ###
number -= quar * 1000000000000000
trin = Math.floor(number / 1000000000000)
# console.log "at line 100 number is: " + number
### trillion ###
number -= trin * 1000000000000
Gn = Math.floor(number / 1000000000)
# console.log "at line 105 number is: " + number
### billion ###
number -= Gn * 1000000000
million = Math.floor(number / 1000000)
# console.log "at line 111 number is: " + number
### million ###
number -= million * 1000000
Hn = Math.floor(number / 1000)
# console.log "at line 117 number is: " + number
### thousand ###
number -= Hn * 1000
Dn = Math.floor(number / 100)
# console.log "at line 123 number is: " + number
### Tens (deca) ###
number = number % 100
# console.log "at line 128 number is: " + number
### Ones ###
tn = Math.floor(number / 10)
one = Math.floor(number % 10)
# tn = Math.floor(number / 1)
change = Math.round((number % 1) * 100)
res = ''
# console.log "before ifs"
if quintillion > 0
res += $scope.convert(quintillion) + ' Quintillion'
if quar > 0
res += $scope.convert(quar) + ' Quadrillion'
if trin > 0
res += $scope.convert(trin) + ' Trillion'
if Gn > 0
res += $scope.convert(Gn) + ' Billion'
if million > 0
res += (if res == '' then '' else ' ') + $scope.convert(million) + ' Million'
if Hn > 0
res += (if res == '' then '' else ' ') + $scope.convert(Hn) + ' Thousand'
if Dn
res += (if res == '' then '' else ' ') + $scope.convert(Dn) + ' Hundred'
# console.log "the result is: " + res
ones = Array('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eightteen', 'Nineteen')
tens = Array('', '', 'Twenty', 'Thirty', 'Fourty', 'Fifty', 'Sixty', 'Seventy', 'Eigthy', 'Ninety')
# console.log "the result at 161 is: " + res
if tn > 0 or one > 0
if !(res == '')
# res += ' and '
res += ' '
# console.log "the result at 164 is: " + res
if tn < 2
res += ones[tn * 10 + one]
# console.log "the result at 168is: " + res
else
res += tens[tn]
if one > 0
res += '-' + ones[one]
# console.log "the result at 173 is: " + res
if change > 0
if res == ''
res = change + "/100"
else
res += ' and ' + change + "/100"
if res == ''
console.log 'Empty = ' + number
res = ''
if +upper == 1
res = res.toUpperCase()
$scope.newCheck.amountInWords = res
return res
$scope.is_numeric = (mixed_var) ->
# console.log "mixed var is: " + mixed_var
(typeof mixed_var == 'number' or typeof mixed_var == 'string') and mixed_var != '' and !isNaN(mixed_var)
Here is another version from me with some unit tests.
Don't use it with numbers larger than Number.MAX_SAFE_INTEGER.
describe("English Numerals Converter", function () {
assertNumeral(0, "zero");
assertNumeral(1, "one");
assertNumeral(2, "two");
assertNumeral(3, "three");
assertNumeral(4, "four");
assertNumeral(5, "five");
assertNumeral(6, "six");
assertNumeral(7, "seven");
assertNumeral(8, "eight");
assertNumeral(9, "nine");
assertNumeral(10, "ten");
assertNumeral(11, "eleven");
assertNumeral(12, "twelve");
assertNumeral(13, "thirteen");
assertNumeral(14, "fourteen");
assertNumeral(15, "fifteen");
assertNumeral(16, "sixteen");
assertNumeral(17, "seventeen");
assertNumeral(18, "eighteen");
assertNumeral(19, "nineteen");
assertNumeral(20, "twenty");
assertNumeral(21, "twenty-one");
assertNumeral(22, "twenty-two");
assertNumeral(23, "twenty-three");
assertNumeral(30, "thirty");
assertNumeral(37, "thirty-seven");
assertNumeral(40, "forty");
assertNumeral(50, "fifty");
assertNumeral(60, "sixty");
assertNumeral(70, "seventy");
assertNumeral(80, "eighty");
assertNumeral(90, "ninety");
assertNumeral(99, "ninety-nine");
assertNumeral(100, "one hundred");
assertNumeral(101, "one hundred and one");
assertNumeral(102, "one hundred and two");
assertNumeral(110, "one hundred and ten");
assertNumeral(120, "one hundred and twenty");
assertNumeral(121, "one hundred and twenty-one");
assertNumeral(199, "one hundred and ninety-nine");
assertNumeral(200, "two hundred");
assertNumeral(999, "nine hundred and ninety-nine");
assertNumeral(1000, "one thousand");
assertNumeral(1001, "one thousand and one");
assertNumeral(1011, "one thousand and eleven");
assertNumeral(1111, "one thousand and one hundred and eleven");
assertNumeral(9999, "nine thousand and nine hundred and ninety-nine");
assertNumeral(10000, "ten thousand");
assertNumeral(20000, "twenty thousand");
assertNumeral(21000, "twenty-one thousand");
assertNumeral(90000, "ninety thousand");
assertNumeral(90001, "ninety thousand and one");
assertNumeral(90100, "ninety thousand and one hundred");
assertNumeral(90901, "ninety thousand and nine hundred and one");
assertNumeral(90991, "ninety thousand and nine hundred and ninety-one");
assertNumeral(90999, "ninety thousand and nine hundred and ninety-nine");
assertNumeral(91000, "ninety-one thousand");
assertNumeral(99999, "ninety-nine thousand and nine hundred and ninety-nine");
assertNumeral(100000, "one hundred thousand");
assertNumeral(999000, "nine hundred and ninety-nine thousand");
assertNumeral(1000000, "one million");
assertNumeral(10000000, "ten million");
assertNumeral(100000000, "one hundred million");
assertNumeral(1000000000, "one billion");
assertNumeral(1000000000000, "one trillion");
assertNumeral(1000000000000000, "one quadrillion");
assertNumeral(1000000000000000000, "one quintillion");
assertNumeral(1000000000000000000000, "one sextillion");
assertNumeral(-1, "minus one");
assertNumeral(-999, "minus nine hundred and ninety-nine");
function assertNumeral(number, numeral) {
it(number + " is " + numeral, function () {
expect(convert(number)).toBe(numeral);
});
}
});
function convert(n) {
let NUMERALS = [
{value: 1000000000000000000000, str: "sextillion"},
{value: 1000000000000000000, str: "quintillion"},
{value: 1000000000000000, str: "quadrillion"},
{value: 1000000000000, str: "trillion"},
{value: 1000000000, str: "billion"},
{value: 1000000, str: "million"},
{value: 1000, str: "thousand"},
{value: 100, str: "hundred"},
{value: 90, str: "ninety"},
{value: 80, str: "eighty"},
{value: 70, str: "seventy"},
{value: 60, str: "sixty"},
{value: 50, str: "fifty"},
{value: 40, str: "forty"},
{value: 30, str: "thirty"},
{value: 20, str: "twenty"},
{value: 19, str: "nineteen"},
{value: 18, str: "eighteen"},
{value: 17, str: "seventeen"},
{value: 16, str: "sixteen"},
{value: 15, str: "fifteen"},
{value: 14, str: "fourteen"},
{value: 13, str: "thirteen"},
{value: 12, str: "twelve"},
{value: 11, str: "eleven"},
{value: 10, str: "ten"},
{value: 9, str: "nine"},
{value: 8, str: "eight"},
{value: 7, str: "seven"},
{value: 6, str: "six"},
{value: 5, str: "five"},
{value: 4, str: "four"},
{value: 3, str: "three"},
{value: 2, str: "two"},
{value: 1, str: "one"}
];
if (n < 0) {
return "minus " + convert(-n);
} else if (n === 0) {
return "zero";
} else {
let result = "";
for (let numeral of NUMERALS) {
if (n >= numeral.value) {
if (n < 100) {
result += numeral.str;
n -= numeral.value;
if (n > 0) result += "-";
} else {
let times = Math.floor(n / numeral.value);
result += convert(times) + " " + numeral.str;
n -= numeral.value * times;
if (n > 0) result += " and ";
}
}
}
return result;
}
}
<script src="http://www.ittutorials.in/js/demo/numtoword.js" type="text/javascript"></script>
HTML - Convert numbers to words using JavaScript</h1>
<input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);" onkeyup="NumToWord(this.value,'divDisplayWords');"
maxlength="9" style="background-color: #efefef; border: 2px solid #CCCCC; font-size: large" />
<br />
<br />
<div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;">
</div>
I think, I have solution that's simpler and easier to understand; it goes by slicing the number, it works up to 99 lakhs crore.
function convert_to_word(num, ignore_ten_plus_check) {
var ones = [];
var tens = [];
var ten_plus = [];
ones["1"] = "one";
ones["2"] = "two";
ones["3"] = "three";
ones["4"] = "four";
ones["5"] = "five";
ones["6"] = "six";
ones["7"] = "seven";
ones["8"] = "eight";
ones["9"] = "nine";
ten_plus["10"] = "ten";
ten_plus["11"] = "eleven";
ten_plus["12"] = "twelve";
ten_plus["13"] = "thirteen";
ten_plus["14"] = "fourteen";
ten_plus["15"] = "fifteen";
ten_plus["16"] = "sixteen";
ten_plus["17"] = "seventeen";
ten_plus["18"] = "eighteen";
ten_plus["19"] = "nineteen";
tens["1"] = "ten";
tens["2"] = "twenty";
tens["3"] = "thirty";
tens["4"] = "fourty";
tens["5"] = "fifty";
tens["6"] = "sixty";
tens["7"] = "seventy";
tens["8"] = "eighty";
tens["9"] = "ninety";
var len = num.length;
if(ignore_ten_plus_check != true && len >= 2) {
var ten_pos = num.slice(len - 2, len - 1);
if(ten_pos == "1") {
return ten_plus[num.slice(len - 2, len)];
} else if(ten_pos != 0) {
return tens[num.slice(len - 2, len - 1)] + " " + ones[num.slice(len - 1, len)];
}
}
return ones[num.slice(len - 1, len)];
}
function get_rupees_in_words(str, recursive_call_count) {
if(recursive_call_count > 1) {
return "conversion is not feasible";
}
var len = str.length;
var words = convert_to_word(str, false);
if(len == 2 || len == 1) {
if(recursive_call_count == 0) {
words = words +" rupees";
}
return words;
}
if(recursive_call_count == 0) {
words = " and " + words +" rupees";
}
var hundred = convert_to_word(str.slice(0, len-2), true);
words = hundred != undefined ? hundred + " hundred " + words : words;
if(len == 3) {
return words;
}
var thousand = convert_to_word(str.slice(0, len-3), false);
words = thousand != undefined ? thousand + " thousand " + words : words;
if(len <= 5) {
return words;
}
var lakh = convert_to_word(str.slice(0, len-5), false);
words = lakh != undefined ? lakh + " lakh " + words : words;
if(len <= 7) {
return words;
}
recursive_call_count = recursive_call_count + 1;
return get_rupees_in_words(str.slice(0, len-7), recursive_call_count) + " crore " + words;
}
Please check out my code pen
If anybody ever wants to do this but in Spanish (en español), here's my code based on Hardik's
function num2str(num, moneda) {
moneda = moneda || (num !== 1 ? "pesos" : "peso");
var fraction = Math.round(__cf_frac(num) * 100);
var f_text = " (" + pad(fraction, 2) + "/100 M.N.)";
return __cf_convert_number(num) + " " + moneda + f_text;
}
function __cf_frac(f) {
return f % 1;
}
function __cf_convert_number(number) {
if ((number < 0) || (number > 999999999)) {
throw Error("N\u00famero fuera de rango");
}
var millon = Math.floor(number / 1000000);
number -= millon * 1000000;
var cientosDeMiles = Math.floor(number / 100000);
number -= cientosDeMiles * 100000;
var miles = Math.floor(number / 1000);
number -= miles * 1000;
var centenas = Math.floor(number / 100);
number = number % 100;
var tn = Math.floor(number / 10);
var one = Math.floor(number % 10);
var res = "";
var cientos = Array("", "cien", "doscientos", "trescientos", "cuatrocientos", "quinientos", "seiscientos", "setecientos", "ochocientos", "novecientos");
if (millon > 0) {
res += (__cf_convert_number(millon) + (millon === 1 ? " mill\u00f3n" : " millones"));
}
if (cientosDeMiles > 0) {
res += (((res == "") ? "" : " ") +
cientos[cientosDeMiles] + (miles > 0 || centenas > 0 || tn > 0 || one < 0 ? (cientosDeMiles == 1 ? "to " : " ") : ""));
}
if (miles > 0) {
res += (((res == "") ? "" : " ") +
__cf_convert_number(miles) + " mil");
}
if (centenas) {
res += (((res == "") ? "" : " ") +
cientos[centenas] + (tn > 0 || one > 0 ? (centenas > 1 ? " " : "to ") : ""));
}
var ones = Array("", "un", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve");
var tens = Array("", "", "veinte", "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", "noventa");
if (tn > 0 || one > 0) {
if (tn < 2) {
res += ones[tn * 10 + one];
}
else {
if (tn === 2 && one > 0)
res += "veinti" + ones[one];
else {
res += tens[tn];
if (one > 0) {
res += (" y " + ones[one]);
}
}
}
}
if (res == "") {
res = "cero";
}
return res.replace(" ", " ");
}
function pad(num, largo, char) {
char = char || '0';
num = num + '';
return num.length >= largo ? num : new Array(largo - num.length + 1).join(char) + num;
}
Result:
num2str(123456789)
"ciento veintitres millones cuatrocientos cincuenta y seis mil setecientos ochenta y nueve pesos (00/100 M.N.)"
I am providing here my solution for converting numbers to the equivalent English words using the Single Loop String Triplets (SLST) Method which I have published and explained in detail here at Code Review with illustration graphics.
Simple Number to Words using a Single Loop String Triplets in JavaScript
The concept is simple and easily coded and is also very efficient and fast. The code is very short compared with other alternative methods described in this article.
The concept also permits the conversion of very vary large numbers as it does not rely on using the numeric/math function of the language and therefore avoids any limitations.
The Scale Array may be increased by adding more scale names if required after "Decillion".
A sample test function is provided below to generate numbers from 1 to 1099 as an example.
A full fancy version is available that caters for adding the word "and" and commas between the scales and numbers to align with the UK and US ways of spelling the numbers.
Hope this is useful.
/************************************************************/
function NumToWordsInt(NumIn) {
/************************************************************
* Convert Integer Numbers to English Words
* Using the Single Loop String Triplets Method
* #Param : {Number} The number to be converted
* For large numbers use a string
* #Return: {String} Wordified Number (Number in English Words)
* #Author: Mohsen Alyafei 10 July 2019
* #Notes : Call separately for whole and for fractional parts.
* Scale Array may be increased by adding more scale
* names if required after Decillion.
/************************************************************/
if (NumIn==0) return "Zero";
var Ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"],
Tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"],
Scale = ["", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion"],
N1, N2, Sep, j, i, h, Trplt, tns="", NumAll = "";
NumIn += ""; // Make NumIn a String
//----------------- code starts -------------------
NumIn = "0".repeat(NumIn.length * 2 % 3) + NumIn; //Create shortest string triplets 0 padded
j = 0; //Start with the highest triplet from LH
for (i = NumIn.length / 3 - 1; i >= 0; i--) { //Loop thru number of triplets from LH most
Trplt = NumIn.substring(j, j + 3); //Get a triplet number starting from LH
if (Trplt !="000") { //Skip empty trplets
Sep = Trplt[2] !="0" ? "-":" "; //Dash only for 21 to 99
N1 = Number(Trplt[0]); //Get Hundreds digit
N2 = Number(Trplt.substr(1)); //Get 2 lowest digits (00 to 99)
tns = N2 > 19 ? Tens[Number(Trplt[1])] + Sep + Ones[Number(Trplt[2])] : Ones[N2];
NumAll += ((h = N1>0 ? Ones[N1] + " Hundred": "") + " " + tns).trim() + " " + Scale[i]+ " ";
}
j += 3; //Next lower triplets (move to RH)
}
//----------------- code Ends --------------------
return NumAll.trim(); //Return trimming excess spaces if any
}
// ----------------- test sample -----------------
console.log(NumToWordsInt(67123))
console.log(NumToWordsInt(120003123))
console.log(NumToWordsInt(123999))
console.log(NumToWordsInt(789123))
console.log(NumToWordsInt(100178912))
console.log(NumToWordsInt(777))
console.log(NumToWordsInt(999999999))
console.log(NumToWordsInt(45))
I know this has been answered but I had been working on this before seeing the question. Doesn't have some small errors found in other answers. Supports up to vigintillion.
const num_text = num => {
const ones = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine"}, _tens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"], tens = {2: "twenty", 3: "thirty", 4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety"}, above_tens = ["thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion"];
var result = [];
if (/^0+$/g.test(num)) return "zero";
num = num.replace(/^0+/g, "").split(/(?=(?:...)*$)/);
for (var count = 0; count < num.length; count++){
var _result = "", _num = num[count];
_num = _num.replace(/^0+/g, "");
if (_num.length == 3){
_result += ones[_num[0]] + " hundred";
_num = _num.substring(1, 3).replace(/^0+/g, "");
if (_num.length > 0) _result += " and ";
}
if (_num.length == 1){
_result += ones[_num];
}else if (_num.length == 2){
if (_num[0] == "1"){
_result += _tens[_num[1]];
}else if (/.0/g.test(_num)){
_result += tens[_num[0]];
}else{
_result += tens[_num[0]] + " " + ones[_num[1]];
}
}
if (_result != ""){
if (num.length - count - 2 >= 0) _result += " " + above_tens[num.length - count - 2];
result.push(_result);
}
}
if (result[result.length - 1].includes("and") || result.length == 1) return result.join(", ");
return result.slice(0, result.length - 1).join(", ") + " and " + result[result.length - 1];
}
<input id="input">
<button onclick="document.getElementById('result').innerHTML = num_text(document.getElementById('input').value)">Convert</button>
<div id="result"></div>
https://stackoverflow.com/a/69243038/8784402
TypeScript Version Based on ES2022 + Fastest
Test on Typescript Playground
Hindi Version
class N2WHindi {
// "शून्य"
private static readonly zeroTo99: string[] =
'|एक|दो|तीन|चार|पाँच|छः|सात|आठ|नौ|दश|ग्यारह|बारह|तेरह|चौदह|पन्द्रह|सोलह|सत्रह|अठारह|उन्नीस|बीस|इक्कीस|बाईस|तेईस|चौबीस|पच्चीस|छब्बीस|सत्ताईस|अट्ठाईस|उनतीस|तीस|इकतीस|बत्तीस|तैंतीस|चौंतीस|पैंतीस|छत्तीस|सैंतीस|अड़तीस|उनतालीस|चालीस|इकतालीस|बयालीस|तैंतालीस|चौवालीस|पैंतालीस|छियालीस|सैंतालीस|अड़तालीस|उनचास|पचास|इक्यावन|बावन|तिरपन|चौवन|पचपन|छप्पन|सत्तावन|अट्ठावन|उनसठ|साठ|इकसठ|बासठ|तिरसठ|चौंसठ|पैंसठ|छियासठ|सड़सठ|अड़सठ|उनहत्तर|सत्तर|इकहत्तर|बहत्तर|तिहत्तर|चौहत्तर|पचहत्तर|छिहत्तर|सतहत्तर|अठहत्तर|उन्यासी|अस्सी|इक्यासी|बयासी|तिरासी|चौरासी|पचासी|छियासी|सत्तासी|अट्ठासी|नवासी|नब्बे|इक्यानबे|बानबे|तिरानबे|चौरानबे|पंचानबे|छियानबे|सत्तानबे|अट्ठानबे|निन्यान्बे'.split(
'|'
);
private static readonly place: string[] = 'हज़ार|लाख|करोड़|अरब|खरब|नील'.split('|');
public static convert(x: string): string {
let n: number = x.length;
x = n == 0 ? '00' : n == 1 || n % 2 == 0 ? '0' + x : x;
n = x.length;
let r: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n > 0) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' सौ ' + r;
}
for (let i = 0; n > 0; i++) {
const v: string = N2WHindi.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WHindi.place[i] + (r ? ' ' + r : '');
}
return r;
}
}
Indian English Version
class N2WIndian {
private static readonly zeroTo99: string[] = [];
private static readonly place: string[] = 'Thousand|Lakh|Crore|Arab|Kharab|Nil'.split('|');
static {
const ones: string[] =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens: string[] = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t: number = Math.floor(i / 10);
const o: number = i % 10;
N2WIndian.zeroTo99.push(t < 2 ? ones[i] : tens[t] + (o ? ' ' + ones[o] : ''));
}
}
public static convert(x: string): string {
let n: number = x.length;
x = n == 0 ? '00' : n == 1 || n % 2 == 0 ? '0' + x : x;
n = x.length;
let r = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (n >= 1) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 1)) - 48];
if (v) r = v + ' Hundred ' + r;
}
for (let i = 0; n > 0; i++) {
const v: string = N2WIndian.zeroTo99[x.charCodeAt((n -= 2)) * 10 + x.charCodeAt(n + 1) - 528];
if (v) r = v + ' ' + N2WIndian.place[i] + (r ? ' ' + r : '');
}
return r;
}
}
International Version
class N2WIntl {
private static readonly zeroTo999: string[] = [];
private static readonly place =
'|Thousand|Million|Billion|Trillion|Quadrillion|Quintillion|Sextillion|Septillion|Octillion|Nonillion|Decillion|Undecillion|Duodecillion|Tredecillion|Quattuordecillion|Quindecillion|Sedecillion|Septendecillion|Octodecillion|Novendecillion|Vigintillion|Unvigintillion|Duovigintillion|Tresvigintillion|Quattuorvigintillion|Quinvigintillion|Sesvigintillion|Septemvigintillion|Octovigintillion|Novemvigintillion|Trigintillion|Untrigintillion|Duotrigintillion|Trestrigintillion|Quattuortrigintillion|Quintrigintillion|Sestrigintillion|Septentrigintillion|Octotrigintillion|Noventrigintillion|Quadragintillion'.split(
'|'
);
static {
const ones =
'|One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen'.split(
'|'
);
const tens = '||Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety'.split('|');
for (let i = 0; i < 100; i++) {
const t = Math.floor(i / 10);
const o = i % 10;
N2WIntl.zeroTo999[i] = t < 2 ? ones[i] : tens[t] + (o == 0 ? '' : ' ' + ones[o]);
}
for (let i = 100; i < 1000; i++) {
const h = Math.floor(i / 100);
const t = Math.floor(i / 10) % 10;
const o = i % 10;
const r = N2WIntl.zeroTo999[h] + ' Hundred';
N2WIntl.zeroTo999[i] = t == 0 && o == 0 ? r : r + ' ' + N2WIntl.zeroTo999[t * 10 + o];
}
}
public static convert(x: string): string {
let n = x.length;
x = n == 0 ? '000' : ((n % 3 === 1) ? '00' : (n % 3 === 2) ? '0' : '') + x;
n = x.length;
let r: string = '';
for (let i = 0; n > 0; i++) {
const v: string =
N2WIntl.zeroTo999[x.charCodeAt((n -= 3)) * 100 + x.charCodeAt(n + 1) * 10 + x.charCodeAt(n + 2) - 5328];
if (v) r = v + (i ? ' ' + N2WIntl.place[i] : '') + (r ? ' ' + r : '');
}
return r;
}
}
const test = () => {
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WHindi.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WHindi.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIndian.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^15 -1 :\n' + '9'.repeat(15) + '\n' + N2WIndian.convert('9'.repeat(15)));
}
{
let n = 5000000;
const test: string = '1234567890';
const t0 = performance.now();
while (n-- > 0) {
N2WIntl.convert(test);
}
const t1 = performance.now();
console.log('1234567890 to 5 Million times: ' + (t1 - t0) + 'ms');
console.log('10^126 -1 :\n' + '9'.repeat(126) + '\n' + N2WIntl.convert('9'.repeat(126)));
}
};
test();
Example to convert currency
const [r, p] = "23.54".split('.');
console.log(`${N2WHindi.convert(r)} रुपया और ${N2WHindi.convert(p)} पैसा`)
console.log(`${N2WIndian.convert(r)} Rupees and ${N2WIndian.convert(p)} Paisa`)
console.log(`${N2WIntl.convert(r)} Dollars and ${N2WIntl.convert(p)} Cents`)
I think this will help you
aTens = [ "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy","Eighty", "Ninety"];
aOnes = [ "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ];
var aUnits = "Thousand";
function convertnumbertostring(){
var num=prompt('','enter the number');
var j=6;
if(num.length<j){
var y = ConvertToWords(num);
alert(y);
}else{
alert('Enter the number of 5 letters')
}
};
function ConvertToHundreds(num)
{
var cNum, nNum;
var cWords = "";
if (num > 99) {
/* Hundreds. */
cNum = String(num);
nNum = Number(cNum.charAt(0));
cWords += aOnes[nNum] + " Hundred";
num %= 100;
if (num > 0){
cWords += " and "
}
}
if (num > 19) {
/* Tens. */
cNum = String(num);
nNum = Number(cNum.charAt(0));
cWords += aTens[nNum - 2];
num %= 10;
if (num > 0){
cWords += "-";
}
}
if (num > 0) {
/* Ones and teens. */
nNum = Math.floor(num);
cWords += aOnes[nNum];
}
return(cWords);
}
function ConvertToWords(num)
{
var cWords;
for (var i = 0; num > 0; i++) {
if (num % 1000 > 0) {
if (i != 0){
cWords = ConvertToHundreds(num) + " " + aUnits + " " + cWords;
}else{
cWords = ConvertToHundreds(num) + " ";
}
}
num = (num / 1000);
}
return(cWords);
}

Categories

Resources