Answered by:
Linq Sum Incorrect Result
Question

I have an double array, then i used linq sum function to total.
Expect result is 90 but exactly result is 89.999999999999986. Why?Here is my code
double[] arr = new double[]{14.6,11.3,9.5,9.2,9,8.6,5,5,5,4.5,4.5,3.8}
var sumResult = arr.sum(d=>d);
expect result is 90
but when i start break point debug the exactly result is 89.999999999999986
 Edited by Sovannara Monday, March 18, 2019 4:48 AM
Answers

I only see 76.999999999999986 when running your code. Did you missed something here?
The casing of "sum" is not correct either.
Btw, check this wiki on strategies on manage floating point error, or just use decimal type instead which has higher precision and will not induce floating point errors in your case.
When use decimal:
decimal[] arr = new decimal[] { 1.6m, 11.3m, 9.5m, 9.2m, 9m, 8.6m, 5m, 5m, 5m, 4.5m, 4.5m, 3.8m }; var sumResult = arr.Sum(d => d); // 77.0
 Edited by cheong00Editor Monday, March 18, 2019 4:31 AM
 Proposed as answer by Wendy ZangMicrosoft contingent staff, Moderator Monday, March 18, 2019 8:06 AM
 Marked as answer by Alberto PoblacionMVP, Moderator Tuesday, April 9, 2019 9:47 PM
All replies

I only see 76.999999999999986 when running your code. Did you missed something here?
The casing of "sum" is not correct either.
Btw, check this wiki on strategies on manage floating point error, or just use decimal type instead which has higher precision and will not induce floating point errors in your case.
When use decimal:
decimal[] arr = new decimal[] { 1.6m, 11.3m, 9.5m, 9.2m, 9m, 8.6m, 5m, 5m, 5m, 4.5m, 4.5m, 3.8m }; var sumResult = arr.Sum(d => d); // 77.0
 Edited by cheong00Editor Monday, March 18, 2019 4:31 AM
 Proposed as answer by Wendy ZangMicrosoft contingent staff, Moderator Monday, March 18, 2019 8:06 AM
 Marked as answer by Alberto PoblacionMVP, Moderator Tuesday, April 9, 2019 9:47 PM
