Created
August 17, 2012 20:45
-
-
Save jmstacey/3382462 to your computer and use it in GitHub Desktop.
Number to Words (Coffeescript)
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
NAMES = ['hundred', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion', 'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion'] | |
WORDS = { '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': 'forteen', '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' } | |
to_words = (number) -> | |
number = number.toString() | |
string = if (number.replace('-', '') == number) then '' else 'negative' | |
number = number.replace('-', '') | |
number = '0' + number while (number.length % 3 != 0) | |
triplets = number.match(/.../g) | |
for triplet, index in triplets | |
string += ' ' + WORDS[triplet[0]] + (if triplet[0] == '0' then '' else " #{NAMES[0]}") if triplet.length == 3 | |
string += if (triplet[1] + triplet[triplet.length - 1]) of WORDS then (' ' + WORDS[triplet[1] + triplet[triplet.length - 1]]) else (' ' + WORDS[(parseInt(triplet[1]) * 10).toString()] + ' ' + WORDS[triplet[triplet.length - 1]]) | |
string += ' ' + NAMES[triplets.length - index - 1] unless index + 1 == triplets.length | |
string.replace(/\s+/g, ' ') | |
# Largest supported integer is 2^53. Anything larger should be passed as a string | |
# console.log to_words "-123456" | |
console.log to_words "-123456789012345678901234567890123456789012345678901234567890" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment