Using a dynamic precision value in number_to_currency based on the decimal value

喜欢而已 提交于 2019-12-11 06:22:56

问题


Thoughout our app we use number_to_currency(value, :precision => 2). However, we now have a requirement whereby the value may need displaying to three or more decimal places, e.g.

0.01  => "0.01"
10    => "10.00"
0.005 => "0.005"

In our current implementation, the third example renders as:

0.005 => "0.01"

What's the best approach for me to take here? Can number_to_currency be made to work for me? If not, how do I determine how many decimal places a given floating point value should be displayed to? sprintf("%g", value) comes close, but I can't figure out how to make it always honour a minimum of 2dp.


回答1:


The following will not work with normal floats, because of precision problems, but if you're using BigDecimal it should work fine.

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


来源:https://stackoverflow.com/questions/3320051/using-a-dynamic-precision-value-in-number-to-currency-based-on-the-decimal-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!