Created
August 27, 2013 19:29
-
-
Save kevbuchanan/6357937 to your computer and use it in GitHub Desktop.
Number in Words
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
VALUES = { 1000000000000 => 'trillion ', 1000000000 => 'billion ', 1000000 => 'million ', 1000 => 'thousand ', 1 => '' } | |
TENS = ['', '', 'twenty ', 'thirty ', 'forty ', 'fifty ', 'sixty ', 'seventy ', 'eighty ', 'ninety '] | |
ONES = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine '] | |
TEENS = ['ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '] | |
def to_word(number) | |
power = 1000**(Math.log10(number).floor / 3) | |
to_write = number / power | |
number_as_word = get_hundreds(to_write) + get_tens(to_write) + get_ones(to_write) + VALUES[power] | |
number_as_word << to_word(number % power) unless number % power == 0 | |
number_as_word.chomp | |
end | |
def get_hundreds(number) | |
hundreds = number / 100 | |
hundreds > 0 ? ONES[hundreds] + 'hundred ' : '' | |
end | |
def get_tens(number) | |
tens = number % 100 / 10 | |
if tens > 0 | |
tens == 1 ? TEENS[number % 100 - 10] : TENS[tens] | |
else | |
'' | |
end | |
end | |
def get_ones(number) | |
ones = number % 10 | |
(number % 100 / 10) != 1 ? ONES[ones] : '' | |
end | |
while number = gets.chomp | |
break if number == '' | |
puts to_word(number.to_i) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment