Skip to content

Instantly share code, notes, and snippets.

@waneka
Created March 11, 2014 05:10
Show Gist options
  • Save waneka/9479825 to your computer and use it in GitHub Desktop.
Save waneka/9479825 to your computer and use it in GitHub Desktop.
Phase 1 in_words function TO ZILLIONS! (with TDD)
ONES_PLACE = {
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine"
}
TENS_PLACE = {
1 => "ten",
2 => "twenty",
3 => "thirty",
4 => "forty",
5 => "fifty",
6 => "sixty",
7 => "seventy",
8 => "eighty",
9 => "ninety"
}
ZILLIONTH_PLACE = {
1 => "thousand",
2 => "million",
3 => "billion",
4 => "trillion",
5 => "quadrillion",
6 => "pentillion"
}
# 10 ^ n*3
# 453 937
def in_words(num)
ZILLIONTH_PLACE.keys.reverse.each do |i|
zeroes = 10**(i*3)
if num >= zeroes
return "#{in_words(num/zeroes)} #{ZILLIONTH_PLACE[i]}" if num%zeroes == 0
return "#{in_words(num/zeroes)} #{ZILLIONTH_PLACE[i]} #{in_words(num%zeroes)}"
end
end
# if num >=1000000000
# return "#{in_words(num/1_000_000_000)} billion" if num%1000000000 == 0
# return "#{in_words(num/1_000_000_000)} billion #{in_words(num%1000000000)}"
# end
# if num >= 1000000
# return "#{in_words(num/1_000_000)} million" if num%1000000 == 0
# return "#{in_words(num/1_000_000)} million #{in_words(num%1000000)}"
# end
# if num >= 1000
# return "#{in_words(num/1000)} thousand" if num%1000 == 0
# return "#{in_words(num/1000)} thousand #{in_words(num%1000)}"
# end
words = ""
if num >= 100
hundreds = num/100
words+= "#{ONES_PLACE[hundreds]} hundred"
num -= hundreds * 100
words += ' ' if num % 100 != 0
end
if num >= 10
tens = num/10
words+= TENS_PLACE[tens]
words += ' ' if num % 10 != 0
num -= (tens * 10)
end
if num > 0
ones = num % 10
words+= ONES_PLACE[ones]
num -= ones
end
words
end
def assert(anything)
raise "Bummer, man" unless anything
end
assert(in_words(1) == "one")
assert(in_words(2) == "two")
assert(in_words(10) == "ten")
assert(in_words(20) == "twenty")
assert(in_words(21) == "twenty one")
assert(in_words(100) == "one hundred")
assert(in_words(101) == "one hundred one")
assert(in_words(122) == "one hundred twenty two")
assert(in_words(1000) == "one thousand")
assert(in_words(1001) == "one thousand one")
assert(in_words(453937) == "four hundred fifty three thousand nine hundred thirty seven")
assert(in_words(1001001) == "one million one thousand one")
assert(in_words(1000000) == "one million")
assert(in_words(1001001001) == "one billion one million one thousand one")
puts 'you got it!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment