Skip to content

Instantly share code, notes, and snippets.

@ForbesLindesay
Created April 26, 2013 14:28
Show Gist options
  • Save ForbesLindesay/5467742 to your computer and use it in GitHub Desktop.
Save ForbesLindesay/5467742 to your computer and use it in GitHub Desktop.
function humanize(num){
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'];
var numString = num.toString();
if (num < 0) throw new Error('Negative numbers are not supported.');
if (num === 0) return 'zero';
//the case of 1 - 20
if (num < 20) {
return ones[num];
}
if (numString.length === 2) {
return tens[numString[0]] + ' ' + ones[numString[1]];
}
//100 and more
if (numString.length == 3) {
if (numString[1] === '0' && numString[2] === '0')
return ones[numString[0]] + ' hundred';
else
return ones[numString[0]] + ' hundred and ' + convert(+(numString[1] + numString[2]));
}
if (numString.length === 4) {
var end = +(numString[1] + numString[2] + numString[3]);
if (end === 0) return ones[numString[0]] + ' thousand';
if (end < 100) return ones[numString[0]] + ' thousand and ' + convert(end);
return ones[numString[0]] + ' thousand ' + convert(end);
}
}
@pablowbk
Copy link

pablowbk commented Dec 5, 2022

Thanks a lot for he gist, it really help me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment