Rails Accuracy Error

When I ran this in my Rails application:

my_envelope.transactions.sum(:amount)

This SQL is displayed in the log files:

SQL (0.3ms)  SELECT SUM("transactions"."amount") AS sum_id FROM "transactions" WHERE (envelope_id = 834498537)

And this value is returned:

<BigDecimal:1011be570,'0.2515999999 9999997E2',27(27)>

As you can see, the value is 25.159999. It should be 25.16. When I run the same SQL in the database, the correct value is returned.

I'm a little confused because I know that there are problems with precision with Floats, but it returns BigDecimal. The SQL column type is decimal. I am using sqlite3 (3.6.17) and sqlite3-ruby (1.3.2). Any ideas?

Update 1

Here are the results when I run it directly using the SQLite3-ruby interface.

$ rails c test
Loading test environment (Rails 3.0.3)
irb(main):001:0> db = SQLite3::Database.new("db/test.sqlite3")
=> #<SQLite3::Database:0x5242020>
irb(main):002:0> db.execute("SELECT SUM(amount) FROM transactions WHERE envelope_id = 834498537")
=> [[25.159999999999997]]

The class of this number is Float. btw, the three numbers he sums up are -40.25, 100, and -34.59.

Update 2

, , sqlite3. ( Ruby Float) sqlite3-ruby, sqlite3-ruby Rails Float. Rails BigDecimal, . Ruby 1.9 Ruby , .

+3
1

, Float, TEXT . "" . , (, sqlite3-ruby).

SELECT CAST(SUM(amount) AS TEXT) FROM transactions WHERE envelope_id = 834498537

, Active Record BigDecimal, Float ISO.

, , transactions. - - .

+2

Source: https://habr.com/ru/post/1783358/


All Articles