decimals in rails database

Update 12/2/2016: DIDNT WORK FOR ME IN RAILS 5?!?!!?!?

For me and my Mac, this works.

$ rails g model Rabbit weight:decimal{4-2}
$ rake db:migrate

That’s creates a maximum 4 digit number with 2 decimals. Now you can add a decimal to your database like so

$ rails c
> Rabbit.create(weight: 10.23)
> Rabbit.first.weight
=>  #< BigDecimal:7ff7f747ab98,'0.2343E4',9(27)>

What the fkkkk? BigDecimal?! Don’t worry dawg, I got your back.

> Rabbit.first.weight.to_s
> "10.23"

In rails console you’ll need to add .to_s, but in your view, the big decimal will display correctly without it.

Also remember how we did a {4-2} after the decimal call? weight:decimal{4-2}. That truly means this field will not store more than 4 digits. For example

Rabbit.create(weight:234.23) Rabbit.last.weight.to_s => "234.2"

It dropped that last digit like a boss.

Post Content