由於精度問題,以下方法不適用於正常的浮點數,但如果您使用的是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
來源
2010-07-23 18:25:59
jdl