Rails:如何将小数打印为百分比? [英] Rails: How to print a decimal as a percent?

查看:24
本文介绍了Rails:如何将小数打印为百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将小数打印为百分比,所以只有句点后的两位数字?

Is there a way to print a decimal as a percentage, so only the two digits after the period?

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

My decimals will always be between 1 and 0, so I suppose it would work to call number.round(2) starting with the third character, but I can't find the syntax for that anywhere.

澄清一下,我希望将数字存储为完整十进制,但打印为百分比.

To clarify, I want the number to be stored as a full decimal, but printed as a percentage.

推荐答案

您可能想要使用 number_to_percentage 方法.在文档中,以下是一些如何使用它的示例:

You are probably going to want to use the number_to_percentage method. From the documentation, here are some examples of how to use it:

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​​:

Or you can write some ruby like the following:

 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   (%)

这篇关于Rails:如何将小数打印为百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆