ruby-on-rails - rails : How to print a decimal as a percent?

标签 ruby-on-rails ruby ruby-on-rails-4 decimal percentage

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

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

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

最佳答案

您可能想要使用 number_to_percentage 方法。来自documentation ,这里有一些如何使用它的例子:

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

关于ruby-on-rails - rails : How to print a decimal as a percent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26455813/

相关文章:

ruby-on-rails - 使用heroku_san gem 时出错:您的 Ruby 版本是 x.x.x,但您的 Gemfile 指定了 x.x.x (Bundler::RubyVersionMismatch)

ruby、gem、rbenv 命令未找到

css - 如何创建评论 View ? Facebook 点赞评论实现(ruby on rails)

ruby-on-rails-4 - Ruby on Rails 连接多个表以及如何提取数据

ruby-on-rails - ruby roo gem : comparison of Fixnum with nil failed (ArgumentError)

ruby-on-rails - 你可以在 Rails 模块中包含之前/之后的过滤器吗?

ruby-on-rails - 用于循环第 n 个嵌套深度的递归函数

ruby-on-rails - 使用带有事件记录的连接表时如何连接模型的多个实例?

ruby-on-rails - 如何使用 3 个或语句编写 Pundit 策略?

ruby - 在多线程 Rails 环境中使用 Redis 的最佳方式是什么? (彪马/Sidekiq)