如何使用 NumberHelper 将 Ruby 中的所有数字格式化为百万

How to format all numbers into millions in Ruby using NumberHelper

Ruby新手在此 - 我正在尝试将任何数字(包括千)转化为百万,然后四舍五入到小数点后2位,例如:

1499962946.140625 => 1499.97
31135762.5 => 31.14
8952392.3125 => 8.95
77896 => 0.08
5342 => 0.01

我已经尝试使用以下方法来做到这一点,但到目前为止它只是正确地四舍五入数百万,而千位保持为千位。我还想从结果字符串中删除 'Million' 和 'Thousand':

number_to_human(1234567.12345, precision: 2, significant: false)
=> "1.2 Million"
number_to_human(1234.12345, precision: 2, significant: false)
=> "1.23 Thousand"

此外,有没有办法保留零,例如1276.40 而不是 1276.4 ?

谢谢!

干嘛呢:

> (31135762.5 / 1000000).round(2)
# => 31.14

如果你想保留零,你可以这样做:

> sprintf('%0.02f', 1276.4)
# => "1276.40"

但是现在你有了一个字符串。

如果你想你也可以把它作为一个函数:

def format_number(num)
  sprintf('%0.02f', num / 1000000)
end

format_number(31135762.5)
# => "31.14"
def doit(n)
  (0.000001 * n).ceil(2)
end
doit(1499962946.140625) #=> 1499.97
doit(31135762.5)        #=>   31.14
doit(8952392.3125)      #=>    8.96
doit(77896)             #=>    0.08
doit(5342)              #=>    0.01

参见Float#ceil

对于第三个示例,问题显示所需结果为 8.95,这是通过简单舍入获得的,但问题指出值应为“...舍入 向上 保留 2 位小数。