1

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
Holger Just
  • 52,918
  • 14
  • 115
  • 123
Neil
  • 4,578
  • 14
  • 70
  • 155
  • Don't store currency as a float. It's never a good idea. Read [this](http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) and/or [this](https://spin.atomicobject.com/2014/08/14/currency-rounding-errors/). – Eli Sadoff Nov 04 '16 at 17:52
  • @EliSadoff it isn't stored as a float. It is stored as an integer. I am simply displaying it as a float. I updated question for clarity. – Neil Nov 04 '16 at 17:53
  • I misread the question. – Eli Sadoff Nov 04 '16 at 17:54
  • 1
    I gave an answer. I don't really think that it needs to be displayed as a float. It's easier, and looks better, to just interpolate it as an integer. – Eli Sadoff Nov 04 '16 at 17:58
  • good point, no reason to display as float. string is better. – Neil Nov 04 '16 at 17:59

3 Answers3

4

Taking advantage of your own implementation:

def cents_to_currency_string(cents)
  return if cents.nil?
  dollars = cents.to_f/100
  '%.2f' % dollars
end
Alexandre Angelim
  • 6,293
  • 1
  • 16
  • 13
1

You can just a little bit edit your method:

def cents_to_currency_string(cents)    
    return if cents.nil? 
    (cents.to_f / 100).to_s.ljust(4,'0')
end
Oleksandr Holubenko
  • 4,310
  • 2
  • 14
  • 28
0

You can do this a few different ways. The easiest way is to do something like this

def display(n)
  if n % 100 < 10
    "$#{n/100}.0#{n%100}"
  else 
    "$#{n/100}.#{n%100}"
  end
end

And then you can display it like this

puts centize(n)
Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61