# Rails Tip: Precision and scale for decimals

> How to specify precision and scale for decimal columns in Rails migrations using BigDecimal

- Author: Curtis Miller
- Published: 2008-04-12
- Categories: rails, how-to
- Canonical URL: https://millarian.com/posts/precision-and-scale-for-ruby-on-rails-migrations/

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:

```ruby
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
  end

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

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](http://www.ruby-doc.org/stdlib/libdoc/bigdecimal/rdoc/index.html) 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?

```ruby
>> 1.2 - 1.0 == 0.2
=> false
```

Yep, BigDecimal handles that…

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

So now, go forth and be accurate.

Also see

- [ActiveRecord::ConnectionAdapters::TableDefinition.column](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#M001222)
- [BigDecimal](http://www.ruby-doc.org/stdlib/libdoc/bigdecimal/rdoc/index.html)
- [Latitude and Longitude in Rails](http://earthcode.com/blog/2006/12/latitude_and_longitude_columns.html)
