Created
April 26, 2013 14:28
-
-
Save ForbesLindesay/5467742 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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
my five year old wanted me to spell out all these insane numbers, so i wrote a norwegian numbers-to-words converter for us.
the approach is sligthly diffferent; a recursive check for string-length/ zeros.
supports "unlimited" numbers within about 20 lines of code.
english version: https://gist.github.com/frdnrdb/853d7b264912b97baa7e9b9f279b59b3