有没有办法将小数打印为百分比,因此只打印句点后的两位数字?
我的小数总是在1和0之间,所以我想从第三个字符开始调用number.round(2)
是可行的,但我在任何地方都找不到它的语法。
为了澄清,我希望将数字存储为全十进制,但打印为percentry。
您可能想要使用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)
请参阅文档