Created
October 28, 2013 23:55
-
-
Save dustinbrownman/7206930 to your computer and use it in GitHub Desktop.
A recursive function that converts numbers in to words.
This file contains hidden or 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
| def numbers_in_words(number) | |
| under_twenty = {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"} | |
| tens = { 20 => "twenty", 30 => "thrity", 40 => "forty", 50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty", 90 => "ninety" } | |
| suffix = {1 => "thousand", 2 => "million", 3 => "billion", 4 => "trillion", 5 => "quadrillion", 6 => "quintillion", 7 => "sextillion", 8 => "septillion", 9 => "octillion", 10 => "nonillion", 11 => "decillion"} | |
| if number < 20 | |
| under_twenty[number] | |
| elsif number < 100 | |
| "#{tens[number - (number % 10)]} #{numbers_in_words(number % 10)}" | |
| elsif number < 1000 | |
| "#{under_twenty[number / 100]} hundred #{numbers_in_words(number % 100)}" | |
| else | |
| suffix_key = Math.log10(number).to_i / 3 | |
| "#{numbers_in_words(number / 10 ** (suffix_key * 3))} #{suffix[suffix_key]} #{numbers_in_words(number % 10 ** (suffix_key * 3))}".rstrip.squeeze(" ") | |
| end | |
| end |
This file contains hidden or 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
| require 'rspec' | |
| require 'numbers_in_words' | |
| describe 'numbers_in_words' do | |
| it 'converts numbers less than 10' do | |
| numbers_in_words(5).should eq "five" | |
| end | |
| it "converts numbers less than 100 into words" do | |
| numbers_in_words(85).should eq "eighty five" | |
| end | |
| it "converts numbers between 10 and 20 into words" do | |
| numbers_in_words(17).should eq "seventeen" | |
| end | |
| it "converts positive numbers less than 1000" do | |
| numbers_in_words(674).should eq "six hundred seventy four" | |
| end | |
| it "converts positive numbers up to one million" do | |
| numbers_in_words(80500).should eq "eighty thousand five hundred" | |
| end | |
| it "handles up to the trillions" do | |
| numbers_in_words(10045067000).should eq "ten billion forty five million sixty seven thousand" | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment