Rails Tip: Precision and scale for decimals

For when you need that little bit of extra accuracy, specifying precision and scale for a decimal column in your Ruby on Rails migration is pretty simple. The precision represents the total number of digits in the number, whereas scale represents the number of digits following the decimal point. To specify the precision and scale, simply pass those as options to your column definition.

For example:

class AddLatLngToAddresses < ActiveRecord::Migration
  def self.up
    add_column :addresses, :lat, :decimal, :precision => 15, :scale => 10
    add_column :addresses, :lng, :decimal, :precision => 15, :scale => 10

  def self.down
    remove_column :addresses, :lat
    remove_column :addresses, :lng

This will allow you to have 10 digits after the decimal point and 15 digits max.

One thing to note, however is that Rails will use BigDecimal as the type for the column. BigDecimal provides support for very large or very accurate floating point numbers. Remember those pesky floating point imprecision errors?

>> 1.2 - 1.0 == 0.2
=> false

Yep, BigDecimal handles that…

>> BigDecimal.new('1.2') - BigDecimal.new('1.0') == BigDecimal.new('0.2')
=> true

So now, go forth and be accurate.

Also see

Posted April 12th, 2008 at 3:52 am in Ruby on Rails | Permalink


  1. Emerson:

    Relatively new to Rails and never took the time to understand this simple idea. I just keep Googling it until today, when I realized it would be much better if I just took a few seconds to understand what 'precision' and 'scale' actually did.

    Thanks for the clear explanation, quick and easy…

  2. PToo:


  3. Drew:

    Yes thanks – it seems like the opposite of what it should be. Scale should mean the size of something and precision should be how precise the rounding is.

  4. @morganmoonjob:

    Thanks for writing this post. I learned last week what precision and scale meant, but this is informative nonetheless. I am trying to find a way to alter the scale of a decimal column using a console command.

  5. sorabh:

    What if we do not mention precision and scale

  6. Joshua Pinter:

    How many page views does this page have?!

    I've been here well over 100 times just myself for reference.

    Thanks for writing this up. It's paid dividends. For me at least.

Leave a response: