Created
October 13, 2012 00:06
-
-
Save BrianJoyce/3882447 to your computer and use it in GitHub Desktop.
numbers_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
| require 'pry' | |
| class NumbersToWords | |
| def initialize | |
| @single = %w[zero one two three four five six seven eight nine ten elevin | |
| twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen] | |
| @tens = %w[twenty thirty fourty fifty sixty seventy eighty ninety] | |
| @words = "" | |
| end | |
| def numbers_to_words(num) | |
| return if num < 1 | |
| case | |
| when num < 20 | |
| singles(num) | |
| num = 0 | |
| when num < 100 && num >= 20 | |
| tens(num) | |
| num -= reduce_num(num, 10) | |
| when num < 1000 && num >= 100 | |
| hundreds(num) | |
| num -= reduce_num(num, 100) | |
| when num < 10000 && num >= 1000 | |
| thousands(num) | |
| num -= reduce_num(num, 1000) | |
| when num < 100000 && num >= 10000 | |
| tenthousands(num) | |
| num -= reduce_num(num, 1000) | |
| when num < 1000000 && num >= 100000 | |
| hundredthousands(num) | |
| num -= reduce_num(num,1000 ) | |
| when num < 10000000 && num >= 1000000 | |
| millions(num) | |
| num -= reduce_num(num, 1000000) | |
| end | |
| numbers_to_words(num) | |
| @words | |
| end | |
| def reduce_num(num, unit) | |
| (num / unit) * unit | |
| end | |
| def singles(i) | |
| @words += @single[i] | |
| end | |
| def tens(i) | |
| i /= 10 | |
| i -= 2 | |
| @words += @tens[i] + " " | |
| end | |
| def hundreds(i) | |
| i /= 100 | |
| singles(i) | |
| @words += " hundred " | |
| end | |
| def thousands(i) | |
| i /= 1000 | |
| singles(i) | |
| @words += " thousand " | |
| end | |
| def tenthousands(i) | |
| ten = i / 1000 | |
| tens(ten) | |
| singles = ten % 10 | |
| singles(singles) if singles > 0 | |
| @words += " thousand " | |
| end | |
| def hundredthousands(i) | |
| hundred = i / 1000 | |
| thousands = i / 10 | |
| hundreds(hundred) | |
| tenthousands(thousands) if hundred % 100 > 0 | |
| @words += " thousand " if hundred % 100 == 0 | |
| end | |
| def millions(i) | |
| i /= 1000000 | |
| singles(i) | |
| @words += " million " | |
| end | |
| end | |
| the_word = NumbersToWords.new | |
| puts the_word.numbers_to_words(1498752) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment