13

Rails migrations: decimal precision and scale

 3 years ago
source link: https://www.devroom.io/2012/08/28/rails-migrations-decimal-precision-and-scale/?utm_campaign=Feed%3A+ariejan+%28ariejan%7Cdevroom.io%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Rails migrations: decimal precision and scale

Posted: 2012-08-28 - Last updated: 2019-06-05

Tagged rails migrations postgresql

I’m always confused when using decimal in a Rails migration. Normally I need to store a value that has 2 or 3 numbers behind the comma (or dot), or decimals.

Let’s say you have a Product model with a discount_percentage attribute. This attribute is currently an integer, only allowing non-decimal values. To allow 2 digit decimal values (e.g. 12.54), you can mak the following migration:

change_column :products, :discount_percentage, :decimal, precision: 5, scale: 2

This will allow you to store values like 80.00, 99.99 and 100.00. There are five digits in the entire number and of those five, two decimals.

It’s not necessary so specify precision and scale as your database will then allow any decimal value it can store.

Read more about the decimal data type in PostgreSQL here: http://www.postgresql.org/docs/9.1/static/datatype-numeric.html

My site is free of ads and trackers. I record privacy-respecting usage statistics with Fathom.

Was this post helpful to you? Why not ☕ Buy me a coffee

Copyright © 1999-2020 Ariejan de Vroom <[email protected]>

Live now; make now always the most precious time. Now will never come again.
    – Jean-Luc Picard


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK