开发者

ruby strategy to convert floating point number with linguistics

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开发者_如何学JAVA" 
 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!


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜