Ruby BigDecimal : increase number of initial digits saved in database

266 views Asked by At

I am facing an issue with Ruby BigDecimal on my Rails 4 app.

I have a "price" attribute in a Thing model, which class is BigDecimal. Whenever I create or update a Thing, I would like to save the "price" attribute with strictly two decimal digits (e.g. "0.00", "10.00", "10.10", "10.01").

But it saves, by default, only one decimal digit if two are not necessary. Here what I insert and what it saved currently :

"0" => "0.0" (instead of "0.00")
"10" => "10.0" (instead of "10.00")
"10.1" => "10.1" (instead of "10.10")
"10.01" => "10.01" (OK)

I don't just want to display the "price" attribute with two decimals (which can be done using "%.2f" % price), I want to save the "price" attribute with two decimal digits in my database. Any way to do so ?

Thanks a lot for your help.

1

There are 1 answers

2
DrewB On BEST ANSWER

What you are describing seems to me to be purely for display purposes. I don't know of any way to save a decimal to a DB with a specific amount of decimals that don't actually add precision unless you save them as a string.

Seems to me you would be best off creating a method on the Thing model that will return price formatted how you want.