I have table with float column (I’m using MySQL, mysql2 gem, everything standard)
create_table :some_table do |t|
t.float :amount
end
I was playing around in console, when i do
a = SomeTable.new
a.amount = 9999.99
a.save!
#9999.99
a.amount
#9999.99
a.reload
a.amount
#9999.99
everything ok
a = SomeTable.new
a.amount = 9999.999
a.save!
#9999.999
a.amount
#9999.999
a.reload
a.amount
#10000.00
as you see ruby (or rails ) rounds the numbers.
Can someone explain me why is that? …or is just me ?
If you want to know all about floats and why they have rounding errors, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.
If you are tying to do currency calculations, don’t use float! Use a fixed point data type.
If you use rails migrations, the decimal type is what you want as described here.