0

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.

Sag
  • 35
  • 4
  • I think your DBMS might be the issue rather than ruby or rails. Which DBMS are you using? (postgres, mysql, sqlite etc) – Max Williams Jun 16 '15 at 15:09
  • 1
    You're worrying about [the wrong thing](https://en.wiktionary.org/wiki/bikeshedding). It is a display problem, not the database or the data type. The values are correct: `0.0` is `0.00` and `10.0` is `10.00`, they just display differently, so format the display correctly. – the Tin Man Jun 16 '15 at 15:48
  • 1
    *But it saves, by default, only one decimal digit if two are not necessary* How did you figured that out ? – David Unric Jun 17 '15 at 01:13
  • 1
    My DBMS is Postgres. – Sag Jun 19 '15 at 12:30
  • In Rails console, when I create a "t" Thing object with a price that is, for example, "10" and then display it by typing "t.price.to_s", I get "10.0". More examples can be found in the original post. – Sag Jun 19 '15 at 12:32

1 Answers1

2

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.

DrewB
  • 3,231
  • 24
  • 22
  • I can indeed format the display of price by doing something as `"%.2f" % price`, but can't we just save it like this (with two digits) in the database ? Currently it is automatically saving one digit, even when it does not add precision value (ex : "10" is saved as "10.0"). – Sag Jun 19 '15 at 12:37
  • 1
    I think you are missing the point. It isn't saved as 10.0. It is saved as a float in the db with value 10. When that comes into ruby it becomes a float with value 10. If you look at that in the console or any other way that uses to_s it will display it with at least 1 decimal (so you know it is a float) but with the fewest decimals needed to show you the value. – DrewB Jun 19 '15 at 16:01