1

I have a product column like so:

t.decimal :price, :precision => 12, :scale => 2

and it keeps returning 500.0 instead of the expected two decimal 500.00. Then I tried manually changing the product price via the console and it'll only save 1 decimal place.

>product.price = 500.00
=> 500.0
>product.price
=> #<BigDecimal:7ff479c6ba40,'0.5E3',9(36)>

How do I get the decimal column to save and return two decimal places?

Ryan.lay
  • 1,741
  • 2
  • 17
  • 30

1 Answers1

6

scale specifies number of digits after the decimal point preserved in the database. Saving 1.234 will round to 1.23, 500.00 will be stored as 500.00.

In Ruby on Rails, they will be represented as a BigDecimal. The BigDecimal will not know about the format that was used in the DB. If its value is 500.0, its to_s method will output it as 500.0 because that's accurate enough.

To format the values as currency, use the number_to_currency helper method.

Also see Ruby on Rails: best method of handling currency / money and Does Ruby have any number formatting classes?

Community
  • 1
  • 1
amiuhle
  • 2,673
  • 1
  • 19
  • 28
  • so is there no way to force the db to return 2 decimals without using a view helper? – Ryan.lay Jul 27 '15 at 09:25
  • but that's not what's happening with my db, 1.234 is being saved as 1.234, and product.price.to_s => "1.234". So the value's not being rounded up even though scale is defined in the schema. – Ryan.lay Jul 27 '15 at 09:33
  • It will only get truncated when it's saved to the db and then restored. Why don't you want to use a view helper? – amiuhle Jul 27 '15 at 09:35
  • Because the values are being sent to another app via an Api. With over 200 currency values over 6 models it'll save a lot of programming time. It's a bit weird really, I was under the impression that scale limits db entries to 2 decimals and returns 2 decimals...apparently not. – Ryan.lay Jul 27 '15 at 09:38
  • It does limit. If you `save` and then `reload` a model, it will truncate `1.234` to `1.23`. – amiuhle Jul 27 '15 at 09:44
  • you're right. It does limit the entry to two decimals. Seems that I'm stuck with one decimal for .00 though. Thanks! – Ryan.lay Jul 27 '15 at 09:49