-
-
Save zz85/5057936 to your computer and use it in GitHub Desktop.
Now support up to 999 trillion. (fixed a flooring error with ~~ and removed unneeded console.log)
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
// Converts a number to english words | |
// Based on https://gist.github.com/bcamarda/3001102 | |
// Refactored and made some changes to support numbers to a hundred (US) trillion | |
// github.com/zz85 | |
var inWords = (function() { | |
var numberHash = { | |
0:"", 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" | |
}; | |
var groups = ['' ,'thousand', 'million', 'billion', 'trillion']; | |
var values = [10e-1, 10e2, 10e5, 10e8, 10e11]; | |
var convertUnder100 = function(n) { | |
if (n in numberHash) return numberHash[n]; | |
return numberHash[~~(n / 10) * 10] + " " + numberHash[n % 10]; | |
} | |
var convertUnder1000 = function(n) { | |
if (n >= 100) return numberHash[~~(n / 100)] + " hundred " + convertUnder100(n % 100).trim(); | |
return convertUnder100(n % 100).trim(); | |
} | |
return function(n){ | |
if (n == 0) return 'zero'; | |
var word = ''; | |
var i = groups.length, v; | |
while (i--) { | |
v = values[i]; | |
if (n >= v) word += convertUnder1000(~~(n / v % 1000)).trim() + " " + groups[i] + " "; | |
} | |
return word.trim(); | |
}; | |
})(); | |
// Tests | |
function test(number) { | |
console.log(number, inWords(number)); | |
} | |
[0, 1, 10, 11, 15, 20, 42, 50, 99, 100, 101, 111, 121, 200, 999, | |
1000, 1001, 1010, 1100, 1234, 123456, 123456789, 123456789123, 123123123123123123, | |
999999999999999].forEach(test); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment