有没有一种方法将小数以百分比的形式打印出来,只保留小数点后两位呢?
我的小数永远在1和0之间,所以我想可能可以从第三个字符开始调用number.round(2)
,但我找不到任何语法。
澄清一下,我希望数字以完整的小数形式存储,但以百分比形式打印出来。
有没有一种方法将小数以百分比的形式打印出来,只保留小数点后两位呢?
我的小数永远在1和0之间,所以我想可能可以从第三个字符开始调用number.round(2)
,但我找不到任何语法。
澄清一下,我希望数字以完整的小数形式存储,但以百分比形式打印出来。
你可能想要使用 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 (%)
您可以使用number_to_percentage
助手将数字以百分比形式打印在视图中。如果您的数字在0到1之间,则可以使用以下方法:
number_to_percentage(@number * 100, precision: 0)
include ActionView::Helpers::NumberHelper
。 (该短语提醒需要在代码中包括指定的ActionView助手模块以使用其中定义的方法和函数) - Warpling