ruby strategy to convert floating point number with linguistics

南楼画角 提交于 2019-12-08 08:51:08

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/4116961/ruby-strategy-to-convert-floating-point-number-with-linguistics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!