1

So I'm writing what I thought was a simple .rb file to convert a float number into a string. The string returns my floating point number in words. So if I have 11.11 then I would have eleven dollars and eleven cents So far I've extended the float class which has worked alright. I'm having trouble with how to convert the 11 cents into eleven cents. en.numwords would kick back eleven point one one. I've thought about trying out a hash to solve my problem where 11=>eleven cents. Any thoughts how I could implement this? Perhaps a better way to implement this?

Here's what I have so far:

 require 'rubygems'
 require 'linguistics'
 Linguistics::use( :en )



 class Float
 def to_test_string
 puts self #check
 puts self.en.numwords
 self.en.numwords
 end

 end

 puts "Enter two great floating point numbers for adding"
 puts "First number"
 c = gets.to_f
 puts "Second number" 
 d = gets.to_f
 e = c+d
 # puts e
 puts e.to_test_string
 puts "Enter a great floating number! Example 10.34"
 a = gets.to_f
 # puts a
 puts a.to_test_string

Thanks for the help! Post some code so I can try ideas out!

Matt
  • 559
  • 6
  • 15
  • 27

2 Answers2

1

Here's one solution: divide the number into two substrings based on the decimal point delimiter, call en.numwords on each substring separately, and then join the resulting strings with "point" between them. Something along the lines of:

require "rubygems"
require "linguistics"
Linguistics::use(:en)

class Float
  def my_numwords
    self.to_s.split('.').collect { |n| n.en.numwords }.join(' point ')
  end
end

(11.11).my_numwords # => eleven point eleven
Yaser Sulaiman
  • 3,311
  • 2
  • 28
  • 25
  • I had considered stripping out the point as well this is a good strategy for wording. Didn't even think about putting numwords in the pipes. – Matt Nov 07 '10 at 18:59
  • Aren't `en` and `numwords` Rails specific? – Andrew Grimm Nov 07 '10 at 22:18
  • @Andrew I don't think so. My code uses `en` and `numwords` from the [Ruby Linguistics Framework](http://deveiate.org/projects/Linguistics/). I've modified the code to make that more explicit. – Yaser Sulaiman Nov 08 '10 at 08:54
0

This problem can be solved by splitting the float into two values: dollars and cents.

require 'rubygems'
require 'linguistics'
Linguistics::use( :en )

class Float
    def to_test_string
        puts self #check

        #Split into dollars and cents
        cents = self % 1
        dollars = self - cents
        cents = cents * 100

        text = "#{dollars.to_i.en.numwords} dollars and #{cents.to_i.en.numwords} cents"

        puts text
        text
    end
end

puts "Enter two great floating point numbers for adding"
puts "First number"
c = gets.to_f
puts "Second number" 
d = gets.to_f
e = c+d
# puts e
puts e.to_test_string
puts "Enter a great floating number! Example 10.34"
a = gets.to_f
# puts a
puts a.to_test_string
Fahad Sadah
  • 2,368
  • 3
  • 18
  • 27