I am a bit confused about a 2-digit decimal gaining an extra 0.000000000000000001 (or so) after going into and out of a database.
This is what I've done: (Rails 3.2.8)
Created a migration:
class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.column :price, :decimal, :precision => 16, :scale => 2
end
end
end
Created a model:
class Item < ActiveRecord::Base
end
Then:
$ rails c
>> i = Item.new
>> i.price = 9.46
>> i.save
>> Item.first.price
=> #<BigDecimal:46b3768,'0.9460000000 000001E1',27(45)>
It's a SQLite database, and it all looks ok in there:
$ rails db
>> select * from items;
1|9.46
Note that the only number I've noticed this happening with is 9.46. Where has the extra 0.00000000000001 come from?
Edit I understand that floating point representations of some numbers are not possible without small errors. But why does Item.first.price
not equal BigDecimal.new('9.46')
? Is SQLite storing a float as opposed to an integer and a number of times it should be divided by 10 (that's what I'd expect from a decimal column)? Or is there some gotcha in ActiveRecord I'm not aware of with retrieving the value from the DB? See below:
$ rails c
>> decimal = BigDecimal.new('9.46')
>> Item.first.price == decimal
=> false