有办法让轨道打印出一个数字与逗号在它?
例如,如果我有一个数字540000000 .34,我可以运行<%= number。函数%>,输出“54,000,000.34”
谢谢!
有办法让轨道打印出一个数字与逗号在它?
例如,如果我有一个数字540000000 .34,我可以运行<%= number。函数%>,输出“54,000,000.34”
谢谢!
当前回答
您需要使用number_with_delimiter方法。例如:
<%= number_with_delimiter(@number, :delimiter => ',') %>
或者,你也可以使用number_with_precision方法来确保数字总是以小数点后两位的精度显示:
<%= number_with_precision(@number, :precision => 2, :delimiter => ',') %>
其他回答
不管有没有Rails,实现这一点的直接方法是:
require 'active_support'
require 'active_support/core_ext/numeric/conversions'
12345.to_s(:delimited) # => "12,345"
12345.6789.to_s(:delimited) # => "12,345.6789"
有关更多选项,请参阅活动支持核心扩展-数字-格式。
如果您经常这样做,但也仅供参考,因为上面没有暗示它,Rails为number_with_delimiter方法提供了合理的默认值。
#inside controller or view
number_with_delimiter(2444323.4)
#=> 2,444,323.30
#inside console
helper.number_with_delimiter(233423)
#=> 233,423
如果使用最典型的方式,则不需要提供分隔符值。
对于Ruby Folks:可以创建函数将逗号设置为大整数。
def number_with_comma(numStr)
return numStr.to_s.gsub(/\B(?=(...)*\b)/, ',')
end
a = number_with_comma 1234567
puts a => 1,234,567
x = 9876543
y = number_with_comma x
puts y => 9,876,543
另一种不使用helper的解决方案:格式化2位小数,然后替换。由,
puts(("%.2f" % 2.5666).gsub('.',','))
>> 2,57
您可以使用来自ActiveSupport的方法
例如:
ActiveSupport::NumberHelper::number_to_currency(10000.1234,{精度:2,单位:"})