Last active
November 5, 2017 11:03
-
-
Save harsh183/95cc0daefa3bdd2101d98d54138c0270 to your computer and use it in GitHub Desktop.
To convert number to words in ruby (for any positive integer)
This file contains 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 toWords(num) | |
units = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] | |
tens = ['', '', 'Twenty', 'Thirty', 'Fourty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'] | |
teens = ['Ten', 'Eleven', 'Tweleve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', | |
'Seventeen', 'Eighteen', 'Nineteen'] | |
units_digit = num % 10 | |
tens_digit = num / 10 | |
number_in_words = "" | |
# Add more powers of ten as needed, otherwise results will come as seven million billion | |
# (which is technically correct, but most likely not desired) | |
powers_of_ten = { 10**9 => 'Billion', | |
10**6 => 'Million', | |
10**3 => 'Thousand', | |
10**2 => 'Hundred' } | |
if num >= 100 | |
powers_of_ten.each { |power_of_ten, word| | |
if (num/power_of_ten > 0) | |
number_in_words += ' ' + toWords(num/power_of_ten) + ' ' + word | |
if units_digit != 0 | |
number_in_words += ' ' + toWords(num % power_of_ten) | |
end | |
break | |
end | |
} | |
elsif num >= 20 | |
number_in_words += tens[tens_digit] | |
if units_digit != 0 | |
number_in_words += ' ' + units[units_digit] | |
end | |
elsif num >= 10 | |
number_in_words += ' ' + teens[units_digit] | |
else | |
number_in_words += ' ' + units[units_digit] | |
end | |
return number_in_words.strip | |
end | |
# Now let's test | |
examples = [43, 53, 23, 20, 60, 42, 18, 15, 10, 9, 0, 99, 153, 100, 1000, 1052, 1729, 1000432231, 45$ | |
examples.each {|num| puts "#{num} => #{toWords(num)}"} | |
# Output | |
# 43 => Fourty Three | |
# 53 => Fifty Three | |
# 23 => Twenty Three | |
# 20 => Twenty | |
# 60 => Sixty | |
# 42 => Fourty Two | |
# 18 => Eighteen | |
# 15 => Fifteen | |
# 10 => Ten | |
# 9 => Nine | |
# 0 => Zero | |
# 99 => Ninety Nine | |
# 153 => One Hundred Fifty Three | |
# 100 => One Hundred | |
# 1000 => One Thousand | |
# 1052 => One Thousand Fifty Two | |
# 1729 => One Thousand Seven Hundred Twenty Nine | |
# 1000432231 => One Billion Four Hundred Thirty Two Thousand Two Hundred Thirty One | |
# 45345890345823345 => Fourty Five Million Billion Three Hundred Fourty Five Million Eight Hundred Twenty Three Thousand Three Hundred Fourty Five |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment