我尝试将数字转换为单词,但我遇到了一个问题:
>> (91.80).en.numwords
=> "ninety-one point eight"我希望是“91.80”。我用的是语言学的gem。你知道解决这个问题的方法吗(最好是使用语言学)。
发布于 2009-12-18 21:18:58
它有点老土,但它是有效的:
'91.80'.split('.').map {|i| i.en.numwords}.join(' point ')
=> "ninety-one point eighty"当你把91.80作为一个浮点型时,ruby去掉了尾随的零,所以它需要从字符串开始才能保留信息。一个更好的例子可能是:
'91.83'.split('.').map {|i| i.en.numwords}.join(' point ')
=> "ninety-one point eighty-three"发布于 2011-02-25 00:05:44
如果您在Ruby1.9中使用Linguistics gem,则需要为en.rb的1060行打补丁
# Ruby 1.8 --> fn = NumberToWordsFunctions[ digits.nitems ]
# Ruby 1.9 removed Array.nitems so we get --> fn = NumberToWordsFunctions[ digits.count{|x| !x.nil?} ]
fn = NumberToWordsFunctions[ digits.count{|x| !x.nil?} ]我们把这个小补丁提交给了作者。
发布于 2009-12-18 22:18:48
我自己得到了答案。
def amount_to_words(number)
unless (number % 1).zero?
number = number.abs if number < 0
div = number.div(1)
mod = (number.modulo(1) * 100).round
[div.to_s.en.numwords, "point", mod.to_s.en.numwords].join(" ")
else
number.en.numwords
end
end和结果:
>> amount_to_words(-91.83)
=> "ninety-one point eighty-three"
>> amount_to_words(-91.8)
=> "ninety-one point eighty"
>> amount_to_words(91.8)
=> "ninety-one point eighty"
>> amount_to_words(91.83)
=> "ninety-one point eighty-three"不过,谢谢你们。你和to_s的想法对我很有帮助。
https://stackoverflow.com/questions/1928080
复制相似问题