0

我尝试将数字转换为单词,但我遇到了问题:

>> (91.80).en.numwords
=> "ninety-one point eight"

我希望它是“九十一点八十”。我使用语言学宝石。你知道一些解决方案吗(更喜欢语言学)。

4

3 回答 3

4

这有点hackish,但它有效:

'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"
于 2009-12-18T13:18:58.493 回答
1

如果您将 Linguistics gem 与 Ruby 1.9 一起使用,则需要修补 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?} ]

我们将小补丁提交给了作者。

于 2011-02-24T16:05:44.170 回答
0

我自己得到了答案。

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 的想法对我很有帮助。

于 2009-12-18T14:18:48.390 回答