Thursday, October 20, 2016

Number To Words in Ruby

Here is a simple and short program that I wrote using Ruby programming language that will ask the user to give a number and then our program will convert or translate the given number into words. 

Add me at Facebook my address is jakerpomperada@gmail.com and jakerpomperada@yahoo.com. 

My email address are the following jakerpomperada@gmail.com and jakerpomperada@yahoo.com. 


My mobile number here in the Philippines is 09173084360.


Program Listing

num_words.rb

def number_words(int)
  numbers_to_name = {
      1000000000000 => "trillion",
      1000000000 => "billion",
      1000000 => "million",
      1000 => "thousand",
      100 => "hundred",
      90 => "ninety",
      80 => "eighty",
      70 => "seventy",
      60 => "sixty",
      50 => "fifty",
      40 => "forty",
      30 => "thirty",
      20 => "twenty",
      19=>"nineteen",
      18=>"eighteen",
      17=>"seventeen", 
      16=>"sixteen",
      15=>"fifteen",
      14=>"fourteen",
      13=>"thirteen",              
      12=>"twelve",
      11 => "eleven",
      10 => "ten",
      9 => "nine",
      8 => "eight",
      7 => "seven",
      6 => "six",
      5 => "five",
      4 => "four",
      3 => "three",
      2 => "two",
      1 => "one"
    }
  str = ""
  numbers_to_name.each do |num, name|
    if int == 0
      return str
    elsif int.to_s.length == 1 && int/num > 0
      return str + "#{name}"      
    elsif int < 100 && int/num > 0
      return str + "#{name}" if int%num == 0
      return str + "#{name} " + number_words(int%num)
    elsif int/num > 0
      return str + number_words(int/num) + " #{name} " + number_words(int%num)
    end
  end
end


loop do
print "\n\n";
print "Number To Words Program"
print "\n\n";
print "Enter a Number : ";
num_test = gets.chomp
num_test = num_test.to_i;
puts "\n\n";
print "The result is :=>  "
print number_words(num_test);
print "\n";
puts "\n\n";
    print "Do you want to continue? (y/n) : "
   answer = gets.chomp.downcase
  if answer == "n"
print "\n\n";
    print "End of Program";
    print "\n\n";
break
  end
end

No comments:

Post a Comment