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 ?
Accepted answer is correct in general (and using decimal instead of float will work around the problem).
However, there's a deeper issue here.
The mysql2 driver isn't specifying the precision it wants mysql to return, so the database is returning truncated results.
You can force mysql to return the full precision by multiplying the amount by a float.
class SomeTable
default_scope -> { select("some_tables.*, amount * 1.0000000000000000 as amount")}
end
a = SomeTable.new
a.amount = 9999.999
a.save!
#9999.999
SomeTable.last.amount
#9999.999
SomeTable.unscoped.last.amount
#10000.00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With