Oll*_*lly 1 ruby ruby-on-rails decimal rounding
虽然我们的应用程序使用number_to_currency(value, :precision => 2)
. 但是,我们现在有一个要求,即该值可能需要显示到三个或更多小数位,例如
0.01 => "0.01"
10 => "10.00"
0.005 => "0.005"
Run Code Online (Sandbox Code Playgroud)
在我们当前的实现中,第三个示例呈现为:
0.005 => "0.01"
Run Code Online (Sandbox Code Playgroud)
我在这里采取的最佳方法是什么?可以number_to_currency
为我工作吗?如果不是,我如何确定给定的浮点值应该显示到多少小数位? sprintf("%g", value)
接近,但我不知道如何让它始终遵守至少 2dp。
由于精度问题,以下内容不适用于普通浮点数,但如果您使用BigDecimal
它应该可以正常工作。
def variable_precision_currency(num, min_precision)
prec = (num - num.floor).to_s.length - 2
prec = min_precision if prec < min_precision
number_to_currency(num, :precision => prec)
end
ruby-1.8.7-p248 > include ActionView::Helpers
ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("10"), 2)
$10.00
ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("0"), 2)
$0.00
ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("12.45"), 2)
$12.45
ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("12.045"), 2)
$12.045
ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("12.0075"), 2)
$12.0075
ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("-10"), 2)
$-10.00
ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("-12.00075"), 2)
$-12.00075
Run Code Online (Sandbox Code Playgroud)