Skip to content

Instantly share code, notes, and snippets.

@elreimundo
Created July 17, 2013 15:04
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 elreimundo/6021398 to your computer and use it in GitHub Desktop.
Save elreimundo/6021398 to your computer and use it in GitHub Desktop.
Not sure how elegant this is, but here is my number-to-its-English-word-counterpart translator
def numwords any_number
bignumwords any_number, []
end
def bignumwords number, big_array
place_names = {1 => 'thousand',
2 => 'million',
3 => 'billion',
4 => 'trillion'}
comma_count = Math.log(number,10).floor / 3
comma_count.downto(1) do |commas|
leading_digits = number / (10**(commas*3))
big_array << smallnumwords(leading_digits)
big_array << place_names[commas]
number = number % (10**(commas*3))
end
big_array << smallnumwords(number)
big_array.join(' ')
end
def smallnumwords smallnumber
words_under_a_hundred smallnumber, []
end
def words_under_a_hundred input_number, the_word_array
num_names = {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'}
if input_number == 0
return the_word_array.join(' ')
elsif input_number >= 100
the_word_array << num_names[input_number/100]
the_word_array << 'hundred'
input_number = input_number % 100
words_under_a_hundred(input_number, the_word_array)
elsif input_number >=20
the_word_array << num_names[(input_number/10)*10]
if input_number%10 != 0
the_word_array << num_names[(input_number%10)]
end
else
the_word_array << num_names[(input_number)]
end
the_word_array.join(' ')
end
puts numwords(3231234151)
puts numwords(1515181)
puts numwords(30845)
puts numwords(100)
puts numwords(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment