Home > Software engineering >  Sum column on datatable with 2 different results
Sum column on datatable with 2 different results

Time:01-24

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

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

i need to sum of this comumns, 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

wich only the last one is correct! my question is WHY the first 2 sum give me 6 as result thanks

CodePudding user response:

Because you aren't casting the r("Totale"), so the iterator sums withouth precission, Try:

Dim Totale As Decimal= dt.AsEnumerable().Sum(Function(r) IIf(IsDBNull(r("Totale")), 0, Convert.ToDecimal(r("Totale"))))

CodePudding user response:

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"))
  •  Tags:  
  • Related