views:

25

answers:

1

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  A: 

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
jdl