How to convert decimal string to string value for dollars and cents in ruby?

I save the cost in my application. The cost is not formatted in the database. For example: 00.00 saves the value 0, 1.00 saves as 1, and 40.50 saves as 40.5

I need to read these values ​​from a database and convert them to strings for dollars and cents. For example: 0 β†’ cost_dollars = "00" and cost_cents = "00", 1 β†’ cost_dollars = "01" and cost_cents = "00", 40.5 β†’ cost_dollars = "40" and cost_cents = "50".

Is there an easy way to do this in ruby ​​on rails? Or does someone have code that does this?

Thanks!

+4
source share
5 answers

You can do this with this little Ruby code:

fmt = "%05.2f" % cost cost_dollars, cost_cents = fmt.split '.' 
+16
source

If you are trying to format dollar values ​​in a view, you should look at number_to_currency in ActionView :: Helpers :: NumberHelper.

 >> bd = BigDecimal.new "5.75" >> include ActionView::Helpers >> number_to_currency(bd) => "$5.75" 

Regarding the decomposition of value into individual dollars and cents, my first question will be: "Why?" If you have a good reason and are dealing with decimals in your database, you can do the following.

 >> bd = BigDecimal.new "5.75" >> "dollars:#{bd.truncate} cents:#{bd.modulo(1) * BigDecimal.new('100')}" => "dollars:5.0 cents:75.0" 
+8
source

number_to_currency nice, but it can get expensive; you may want to collapse yourself if you need to call it many times.

You should be aware that using float to store currency can be problematic ( and see ) if you do a lot of calculations based on these values. One solution is to use integers for currency and cents. This is similar to the approach used by the plugin. Another solution is to use the decimal type in your migration, which should work ready for modern versions of Rails (> 1.2):

 add_column :items, :price, :decimal, :precision => 10, :scale => 2 

( :scale - the number of places that have passed after the decimal place :precision - the total number of digits.) This will allow you to BigDecimal objects in Rails, which are a little more difficult to work with, but not so bad.

Both integer and decimal approaches are slightly slower than floating point. I use currency floats in some places because I know that I don’t need to do value calculations in Rails, but only store and display them. But if you need accurate currency calculations, do not use floats.

+7
source

Instead of saving as a decimal sum, store as an integer number of cents. Thus, 1 dollar is stored as 100 in the database.

Alternatively, if you don't mind a bit of overhead, check ".". in the database. If it exists, divide it by "." And parse the fragments as integers.

+5
source

sprintf is your friend here:

 cost_dollars = sprintf('%02.f', cost) cost_cents = sprintf('%.2f', cost) 
+2
source

All Articles