Skip to content

Instantly share code, notes, and snippets.

@timothyandrew
Created October 12, 2011 13:29
Show Gist options
  • Save timothyandrew/1281224 to your computer and use it in GitHub Desktop.
Save timothyandrew/1281224 to your computer and use it in GitHub Desktop.
Number in 'Words'

README

  • This ruby script converts a number to it's text form. For example, 542 is five hundred and forty two.

  • Use the download button above to grab a copy.

  • This requires a ruby version > 1.9

$ ruby -v  
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.0.0]
  • To run, first make the scripts executable.
$ cd path/to/downloaded/files/
$ chmod 777 *.rb
  • And pass in a number to numtotext.rb
$ ./numtotext.rb 1234567
twelve lakh thirty four thousand five hundred and sixty seven
#!/usr/bin/env ruby
def numToText(strNum)
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
others = ["", "", "hundred", "thousand", "lakh", "crore"]
# Keep track of how many of each denomination make up the next larger denomination.
# For example, 100 lakhs make a crore. Maps to the indexes of 'others'
denomination_size = [nil, nil, 10, 100, 100, 100000]
output = ""
#Last digit
if strNum.length == 1
if strNum.to_i == 0
return "zero"
end
return ones[strNum.to_i]
end
#Last two digits
if strNum[-2..-1].to_i < 20
output = ones[strNum[-2..-1].to_i]
else
output = ones[strNum[-1].to_i]
output = tens[strNum[-2].to_i] + " " + output
end
#All other digits
strNum.reverse!
i = 2
j = 2
while i < strNum.length
d_length = denomination_size[j].to_s.length - 1
d = others[j]
if i==2 and output.length != 0
output = "and " + output
end
# Recursively get the number before the denomination. For example the 'fifty' in 'fifty thousand'
subOutput = numToText(strNum[i...i+d_length].reverse)
if(subOutput != "zero" and subOutput.strip.length != 0)
output = d + " " + output
output = subOutput + " " + output
end
i = i + d_length
j = j + 1
end
return output.strip
end
if ARGV.length == 1
puts numToText ARGV[0].strip
end
#!/usr/bin/env ruby
require './numtotext'
require 'test/unit'
class TestNumToText < Test::Unit::TestCase
def test_numbers
assert_equal("twelve", numToText("12"))
assert_equal("zero", numToText("0"))
assert_equal("five lakh fifty thousand and forty two", numToText("550042"))
assert_equal("one hundred", numToText("100"))
assert_equal("twelve thousand", numToText("12000"))
assert_equal("twelve thousand three hundred and forty five", numToText("12345"))
assert_equal("one hundred and twenty three", numToText("123"))
assert_equal("five hundred and four", numToText("504"))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment