Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jmstacey
Created August 17, 2012 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmstacey/3381514 to your computer and use it in GitHub Desktop.
Save jmstacey/3381514 to your computer and use it in GitHub Desktop.
Number to Words (Ruby)
NAMES = ['hundred', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion', 'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion']
WORDS = Hash['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' ]
def to_words(number)
triplets = number.to_s.gsub('-', '').split(//).each_slice(3).to_a.each { |a| a.insert(0, '0') while a.size % 3 != 0 }
string = number < 0 ? 'negative' : ''
triplets.each_with_index do |triplet, triplets_index|
string += ' ' + WORDS[triplet.first] + (triplet.first == '0' ? '' : " #{NAMES[0]}") if triplet.size == 3
string += WORDS.include?(triplet[1] + triplet.last) ? (' ' + WORDS[triplet[1] + triplet.last]) : (' ' + WORDS[(triplet[1].to_i * 10).to_s] + ' ' + WORDS[triplet.last])
string += ' ' + NAMES[triplets.size - triplets_index - 1] unless triplets_index + 1 == triplets.size
end
string.gsub(/ +/, ' ').strip
end
p to_words -123_456_789_012_345_678_901_234_567_890_123_456_789_012_345_678_901_234_567_890
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment