Skip to content

Instantly share code, notes, and snippets.

@austinwang
Created June 15, 2012 21:10
Show Gist options
  • Save austinwang/2938714 to your computer and use it in GitHub Desktop.
Save austinwang/2938714 to your computer and use it in GitHub Desktop.
in_words
module InWords
def in_words
ones = ["", "one","two","three","four","five","six","seven","eight","nine"]
tens = ["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
big_nums = ["hundred","thousand", "million", "billion",]
numStr = self.to_s
numLength = numStr.length
word = ""
if self == 1000000000000
return "one trillion"
end
if numLength == 1
[ones[self]].join(" ").rstrip
else
# Check for teens
if (numLength == 2 || numLength == 5 || numLength == 8 || numLength == 11) && (numStr[0] == "1")
case numLength
when 2
[tens[numStr[0,2].to_i]].join(" ").rstrip
when 5
[tens[numStr[0,2].to_i],big_nums[1],numStr[2,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 8
[tens[numStr[0,2].to_i],big_nums[2],numStr[2,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 11
[tens[numStr[0,2].to_i],big_nums[3],numStr[2,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
end
else
case numLength
when 2
[tens[numStr[0].to_i],numStr[1,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 3
[ones[numStr[0].to_i],big_nums[0],numStr[1,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 4
[ones[numStr[0].to_i],big_nums[1],numStr[1,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 5
[tens[numStr[0].to_i],ones[numStr[1].to_i],big_nums[1],numStr[2,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 6
[ones[numStr[0].to_i],big_nums[0],numStr[1,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 7
[ones[numStr[0].to_i],big_nums[2],numStr[1,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 8
[tens[numStr[0].to_i],ones[numStr[1].to_i],big_nums[2],numStr[2,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 9
[ones[numStr[0].to_i],big_nums[0],numStr[1,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 10
[ones[numStr[0].to_i],big_nums[3],numStr[1,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 11
[tens[numStr[0].to_i],ones[numStr[1].to_i],big_nums[3],numStr[2,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
when 12
[ones[numStr[0].to_i],big_nums[0],numStr[1,numLength].to_i.in_words].join(" ").rstrip.gsub(" "," ")
end
end
end
end
end
class Fixnum
include InWords
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment