SQLite: How to Handle Precision Loss with REAL Data Type During Calculations
I've encountered a strange issue with I'm writing unit tests and I'm working on a personal project and I'm stuck on something that should probably be simple... I'm working with SQLite 3.36.0 and I've noticed some unexpected results when performing arithmetic operations on REAL data types. I have a table that stores prices as REAL values, and when I try to calculate a total price by summing these values, the result seems to lose precision. For example, when I run the following query: ```sql SELECT SUM(price) AS total_price FROM products; ``` I expected the total to be precise, but instead, I'm getting results that are slightly off, such as 99.999999999 instead of 100.00. I've checked the data types and confirmed they are set to REAL. To troubleshoot, I also tried casting the prices to INTEGER before summing them, but that led to rounding issues, which is not acceptable for my application. Hereβs a small snippet of how I insert data into the table: ```sql CREATE TABLE products (id INTEGER PRIMARY KEY, price REAL); INSERT INTO products (price) VALUES (33.33), (33.33), (33.34); ``` I considered using the `round()` function in my query, like this: ```sql SELECT ROUND(SUM(price), 2) AS total_price FROM products; ``` However, I'm not sure if this is the best approach or if it might mask underlying precision issues. Is there a better way to manage floating-point arithmetic in SQLite to avoid precision loss? Should I be using a different data type, or is there a recommended best practice for handling such calculations? Any insights would be greatly appreciated! I recently upgraded to Sql 3.11. Has anyone else encountered this? Could someone point me to the right documentation? I've been using Sql for about a year now. Could this be a known issue?