'Sum column on datatable with 2 different results

I have a datatable with a Column: Total
this is the datatable:

Totale (datatype: decimal)
2,9 
2,9

I need to sum of these columns, then I tried this code:

 Dim Totale As Double = dt.AsEnumerable().Sum(Function(r) IIf(IsDBNull(r("Totale")), 0, r("Totale")))
Dim Totale As Decimal= dt.AsEnumerable().Where(Function(r) IsDBNull(r("Totale")) = False).Sum(Function(r) r("Totale"))
  Dim Totale As Decimal= Convert.ToDecimal(dt.Compute("SUM(Totale)", "Totale is not null"))

This gives me the result of:

6
6
5,8

which only the last one is correct!

Why do the first 2 sum give me 6 as result?



Solution 1:[1]

It seems like Sum treats the values as integers which causes the rounding. You could try and typecast the values with CDec.

Dim Totale As Double = dt.AsEnumerable().Sum(Function(r) IIf(IsDBNull(r("Totale")), CDec(0), CDec(r("Totale"))))
Dim Totale As Decimal= dt.AsEnumerable().Where(Function(r) IsDBNull(r("Totale")) = False).Sum(Function(r) CDec(r("Totale")))
Dim Totale As Decimal= Convert.ToDecimal(dt.Compute("SUM(Totale)", "Totale is not null"))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sebastian Siemens