SQLite Forum

Division by decimals wrongly returning a rounded int result (works fine when casting to real)
Login
Hi Thiago, there's been good and accurate replies to this post, showing what is correct and why.

However, on the off chance you were just interested in a solution, consider the following sql where both table t's columns are INTeger (not even Decimal or Numeric) and see what works and do not work when forcing the calculation types:

```

CREATE TABLE t(a INT, b INT);

INSERT INTO t VALUES
 (10,1)
,(10,2)
,(10,3)
,(10,4)
,(10,5)
,(10,6)
;


SELECT a / b FROM t;   -- Integer division only

  -- a / b
  -- -----
  --   10 
  --   5  
  --   3  
  --   2  
  --   2  
  --   1  


SELECT CAST(a / b AS REAL) FROM t;  -- Not useful

  -- CAST(a / b AS REAL)   
  -- ---------
  --    10.0  
  --    5.0   
  --    3.0   
  --    2.0   
  --    2.0   
  --    1.0   


SELECT (CAST(a AS REAL) / b) FROM t;  -- Casting one or both values

  -- (CAST(a AS REAL) / b)
  -- --------------------
  --                 10.0
  --                  5.0
  --     3.33333333333333
  --                  2.5
  --                  2.0
  --     1.66666666666667


SELECT ((a * 1.0) / b) FROM t;    -- Using another calculation to force float

  --      ((a * 1.0) / b)
  -- --------------------
  --                 10.0
  --                  5.0
  --     3.33333333333333
  --                  2.5
  --                  2.0
  --     1.66666666666667


SELECT (a / (b * 1.0)) FROM t;    -- etc.

  --      (a / (b * 1.0))
  -- --------------------
  --                 10.0
  --                  5.0
  --     3.33333333333333
  --                  2.5
  --                  2.0
  --     1.66666666666667


```

Perhaps an adjusted query is all you need, if other fixes are off the table / slow.