Jake
Jake

Reputation: 39

Formatting a float to a minimum number of decimal places

I'm storing a decimal in rails and I need to have it display as a currency as such:

11.1230 => "$11.123"
11.1000 => "$11.10"
11.0100 => "$11.01"
11.1234 => "$11.1234"

Any easy way to do this?

Upvotes: 3

Views: 4773

Answers (4)

Dylan Markow
Dylan Markow

Reputation: 124449

Edit: Looks like this is Rails 3 specific, as Rails 2's number_with_precision method doesn't include the strip_insignificant_zeros option:

You can pass some options to number_to_currency (a standard Rails helper):

number_to_currency(11.1230, :precision => 10, :strip_insignificant_zeros => true)
# => "$11.123"

You need to provide a precision in order for the strip_insignificant_zeros option to work, though, otherwise the underlying number_with_precision method never gets called.

Upvotes: 5

Phrogz
Phrogz

Reputation: 303391

def pad_number( number, min_decimals=2 )
  s = "%g" % number
  decimals = (s[/\.(\d+)/,1] || "").length
  s << "." if decimals == 0
  s << "0"*[0,min_decimals-decimals].max
end
puts [ 11.123, 11.1, 11.01, 11.1234, 11 ].map{ |n| pad_number(n) }
#=> 11.123
#=> 11.10
#=> 11.01
#=> 11.1234
#=> 11.00

Upvotes: 5

DigitalRoss
DigitalRoss

Reputation: 146143

So, convert it to three decimal fraction digits and then remove the final one if and only if it's a zero.

s.sub(/0$/, '')

Upvotes: -1

Kombo
Kombo

Reputation: 2381

If you want to store as a float, you can use the number_to_currency(value) method in yours views for printing something that looks like $.

Correct me if I'm wrong (as I've rarely dealt with currency) but I think the conventional wisdom is to store dollar values as integers. That way you won't have to deal with funky float math.

Upvotes: 4

Related Questions