0

I am facing this issue with the SQL SUM() function I have three values that have the sum equals to zero as you can see the values but with the SUM() function the answer is that strange values as shown.

select Qty
from Stock
where ProductCode = '5LINE-15-1-30RU' 
    

Output:

1. 49.72
2. -31.065
3. -18.655

Whereas

select sum(Qty)
from Stock
where ProductCode = '5LINE-15-1-30RU'

Output:

-3.5527136788005E-15

The result have to be 0 but I got this awkward value.

Column Qty is a float.

3
  • The datatype for Qty column is float Commented Dec 20, 2020 at 22:35
  • 4
    For all practical purposes, -3.5527136788005E-15 is zero. Commented Dec 20, 2020 at 22:44
  • I'd suggest to use a ROUND function in order to trim these extra digits, which for the float type could lead to these bizarre 0.0xxxxE-16 results Commented Dec 21, 2020 at 0:14

1 Answer 1

12

You are using a float datatype which stores values as approximations c.f.

Approximate-number data types for use with floating point numeric data. Floating point data is approximate; therefore, not all values in the data type range can be represented exactly.

For cases when you need precision, e.g. when you need decimal/int values you should use a decimal/int datatype. Its pretty rare that you would use a float. If you are unable to change the column datatype you can convert it before summing e.g.

DECLARE @Test TABLE (Qty FLOAT);

INSERT INTO @Test (Qty)
VALUES
(49.72),
(-31.065),
(-18.655);

SELECT SUM(Qty)
    , SUM(CONVERT(money,Qty))
FROM @Test;

Returns:

FloatSum ConvertedSum
-3.5527136788005E-15 0.00

Not the answer you're looking for? Browse other questions tagged or ask your own question.