Rails:如何将小数打印为百分比?

21

有没有一种方法将小数以百分比的形式打印出来,只保留小数点后两位呢?

我的小数永远在1和0之间,所以我想可能可以从第三个字符开始调用number.round(2),但我找不到任何语法。

澄清一下,我希望数字以完整的小数形式存储,但以百分比形式打印出来。

2个回答

31

你可能想要使用 number_to_percentage 方法。从文档中,以下是一些使用它的示例:

number_to_percentage(100)                                        # => 100.000%
number_to_percentage("98")                                       # => 98.000%
number_to_percentage(100, precision: 0)                          # => 100%
number_to_percentage(1000, delimiter: '.', separator: ',')       # => 1.000,000%
number_to_percentage(302.24398923423, precision: 5)              # => 302.24399%
number_to_percentage(1000, locale: :fr)                          # => 1 000,000%
number_to_percentage("98a")                                      # => 98a%
number_to_percentage(100, format: "%n  %")                       # => 100  %

选项:

:locale - Sets the locale to be used for formatting (defaults to current locale).
:precision - Sets the precision of the number (defaults to 3).
:significant - If true, precision will be the # of significant_digits. If false, the # of fractional digits (defaults to false).
:separator - Sets the separator between the fractional and integer digits (defaults to “.”).
:delimiter - Sets the thousands delimiter (defaults to “”).
:strip_insignificant_zeros - If true removes insignificant zeros after the decimal separator (defaults to false).
:format - Specifies the format of the percentage string The number field is %n (defaults to “%n%”).

或者您可以编写如下Ruby代码:

 class Numeric
   def percent_of(n)
    self.to_f / n.to_f * 100.0
   end
 end

p (1).percent_of(10)    # => 10.0  (%)
p (200).percent_of(100) # => 200.0 (%)
p (0.5).percent_of(20)  # => 2.5   (%)

5
我很好奇,如果你要从Rails文档中复制粘贴所有内容,为什么不直接提供一个链接呢?或者这是在Stackoverflow上回答问题的首选方式吗? - Alireza
10
@Ali,实际上,这通常是做这件事的最好方法。虽然这个答案应该通过一个链接引用Rails文档,但仅提供一个链接并不是StackOverflow的最佳实践。链接可能会随着时间过去而失效,或者文档可能会更改,使答案变得不太有用。因此,如果提供了链接会更好,但这个答案比仅仅提供文档链接要好。 - Charles Caldwell
5
对于懒惰的人,你需要使用include ActionView::Helpers::NumberHelper。 (该短语提醒需要在代码中包括指定的ActionView助手模块以使用其中定义的方法和函数) - Warpling

7

您可以使用number_to_percentage助手将数字以百分比形式打印在视图中。如果您的数字在0到1之间,则可以使用以下方法:

number_to_percentage(@number * 100, precision: 0) 

请查看文档

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接