Skip to content

Instantly share code, notes, and snippets.

@Pcushing
Created June 14, 2012 02:29
Show Gist options
  • Save Pcushing/2927735 to your computer and use it in GitHub Desktop.
Save Pcushing/2927735 to your computer and use it in GitHub Desktop.
Numbers in Words with recursion up to 1 trillion
class Fixnum
def in_words
ten = 10
hundred = 100
thousand = 1_000
million = 1_000_000
billion = 1_000_000_000
trillion = 1_000_000_000_000
digit_words = { 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", 0 => "zero" }
if (self % trillion) < self
"#{ (self / trillion).in_words } trillion"
elsif (self % billion) < self
"#{ (self / billion).in_words } billion #{ (self % billion).in_words }".strip
elsif (self % million) < self
"#{ (self / million).in_words } million #{ (self % million).in_words }".strip
elsif (self % thousand) < self
"#{ (self / thousand).in_words } thousand #{ (self % thousand).in_words }".strip
elsif (self % hundred) < self
"#{ (self / hundred).in_words } hundred #{ (self % hundred).in_words }".strip
elsif (self < 99) && (self >= 20)
"#{ digit_words[self / ten * ten] } #{ (self % ten).in_words }".strip
elsif (self >=10) && (self < 20)
"#{ digit_words[self] }"
else
"#{ digit_words[self] }"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment