var nameThatNumber = function() {
var names = {
10: 'ten',
1: 'one', 11: 'eleven',
2: 'two', 12: 'twelve', 20: 'twenty',
3: 'three', 13: 'thirteen', 30: 'thirty',
4: 'four', 14: 'fourteen', 40: 'fourty',
5: 'five', 15: 'fifteen', 50: 'fifty',
6: 'six', 16: 'sixteen', 60: 'sixty',
7: 'seven', 17: 'seventeen', 70: 'seventy',
8: 'eight', 18: 'eighteen', 80: 'eighty',
9: 'nine', 19: 'nineteen', 90: 'ninety',
100: 'hundred',
k1: 'thousand',
k2: 'million',
k3: 'billion'
};
function stringify(num) {
if(num < 1000) {
return triade(num);
}
var triades = [];
var n = num;
while(n) {
triades.push(n % 1000);
n = Math.floor(n / 1000);
}
return triades.map(function(n, i) {
var t = triade(n);
if(t === '') {
return '';
}
var nm = ' ' + (names['k' + i] || '');
return t + nm;
}).reverse().join(' ').replace(/\s+/g, ' ').trim();
}
function triade(num) {
var n = num;
if(n === 0) {
return '';
}
if(n <= 20) {
return names[n];
}
var result = '';
if(n >= 100) {
result = names[Math.floor(n / 100)] + ' ' + names[100];
}
n %= 100;
if(n === 0) {
return result;
}
if(result !== '') {
result += ' and ';
}
if(n <= 20) {
return result + names[n];
}
result += names[Math.floor(n / 10) * 10];
n %= 10;
if(n !== 0) {
result += ' ' + names[n];
}
return result;
}
return function nameThatNumber(num) {
var n = Math.abs(parseInt(num));
if(isNaN(n)) {
return 'Not a number!';
}
if(n === 0) {
return 'zero';
}
return (num < 0 ? 'minus ' : '') + stringify(n);
};
}();