Rails:如何以百分比形式打印小数?

15 ruby ruby-on-rails decimal percentage ruby-on-rails-4

有没有办法以百分比形式打印小数,所以只有两个数字后?

我的小数将始终在1和0之间,所以我想它可以number.round(2)用第三个字符开始调用,但我无法在任何地方找到它的语法.

为了澄清,我希望将数字存储为完整小数,但以百分比形式打印.

Joe*_*oel 24

您可能想要使用该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  %
Run Code Online (Sandbox Code Playgroud)

选项:

: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%”).
Run Code Online (Sandbox Code Playgroud)

或者你可以像下面这样写一些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   (%)
Run Code Online (Sandbox Code Playgroud)

  • @Ali实际上,这主要是最好的方法.虽然这个答案确实应该将Rails文档与链接相关联,但仅提供链接并不是StackOverflow的最佳实践.链接可能会随着时间的推移而中断,或者文档可能会更改,从而导致答案不再有用 所以,是的,如果提供了一个链接会很好,但这个答案比文档链接更好. (10认同)
  • 我只是好奇,如果你要复制并粘贴rails文档中的所有内容,为什么不提供链接呢?或者这是在Stackoverflow上回答问题的首选方式? (5认同)
  • 对于懒惰,你需要`include ActionView :: Helpers :: NumberHelper` (4认同)

Ali*_*eza 6

您可以使用number_to_percentage帮助程序在视图中以百分比形式打印数字.如果您的号码在0到1之间,那么您可以通过以下方式实现:

number_to_percentage(@number * 100, precision: 0) 
Run Code Online (Sandbox Code Playgroud)

看文档