因此,我编写了一个简单的.rb文件,将浮点数转换为字符串。该字符串以单词形式返回浮点数。所以如果我有11.11,那么我就有11美元11美分,到目前为止,我已经扩展了float类,它运行良好。我不知道怎么把11美分换成11美分。en.numwords会反击11点1。我曾想过尝试一种散列来解决我的问题,其中11=>eleven是美分。有什么想法可以让我实现这一点吗?也许实现这一点的更好方法是什么?
这是我到目前为止所知道的:
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谢谢你的帮助!发布一些代码,这样我就可以尝试一些想法了!
发布于 2010-11-07 17:00:52
这个问题可以通过将浮点数拆分为两个值来解决:美元和美分。
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发布于 2010-11-07 17:00:32
这里有一个解决方案:根据小数点分隔符将数字分成两个子串,分别对每个子串调用en.numwords,然后用" point“连接结果字符串。大致是这样的:
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 elevenhttps://stackoverflow.com/questions/4116961
复制相似问题