Rails中人类可读的小数?

时间:2013-09-11 20:17:42

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 ruby-on-rails-4 pluralize

我喜欢Rails中的pluralize方法。我希望有一个类似的小数字机制,它们可以更具人性化。例如,这将是理想的:

> include ActionView::Helpers::TextHelper
> pluralize(2.0, 'donut')
 => "2.0 donuts" 
> pluralize_and_humanize(2.0, 'donut')
 => "2 donuts"
> pluralize_and_humanize(2.5, 'donut')
 => "2 and a half donuts"
> pluralize_and_humanize(1.0, 'donut')
 => "1 donut"
> pluralize_and_humanize(0.5, 'donut')
 => "half a donut"
> pluralize_and_humanize(0.75, 'donut')
 => "3/4 of a donut"

内置于导轨中的任何东西?我可以使用任何宝石吗?

1 个答案:

答案 0 :(得分:1)

实际上,我觉得我有东西给你。

在项目中设置rails fractions plugin。然后,编写自己的帮助器,如下所示:(伪代码)

def pluralize_and_humanize(number, string)
  split number into integer and fractional part -> whole, fraction

  convert fraction to [nice_fraction][2] if there is a fractional component

  output whole number + nice_fraction + pluralized string
end

现在,我没有帮你输出“半”或“和四分之一”,但我认为“2 1/2”至少会优于2.5。