Neil Neil - 1 month ago 8
Ruby Question

Show two decimal digits in float with one decimal digit

I have money in database stored as

cents
via integer type. When displaying: I convert it to a float because I want to display the amount in dollar amounts. I always want to display the number with two digits:

ex:

5000 => 50.00
500 => 5.00
50 => 0.50
5 => 0.05
0 => 0.00


The toughest one is getting the
50
to convert to
0.50
because since it is a float it wants to convert to
0.5
.

Current method which doesn't work:

def cents_to_currency_string
return if cents.nil?
(cents.to_f / 100)
end

Answer

Taking advantage of your own implementation:

def cents_to_currency_string(cents)
  return if cents.nil?
  dollars = cents.to_f/100
  '%.2f' % dollars
end
Comments