Issue while adding number

Samoj Bhattarai 20 Reputation points
2023-05-25T04:08:52.82+00:00

The following code returns

SUM : 5.820766091346741E-11 instead of 0. What is the solution for this?

List<double> numbers = new List<double>();
numbers.Add(0);
numbers.Add(570056.52);
numbers.Add(0);
numbers.Add(13270);
numbers.Add(90);
numbers.Add(12565);
numbers.Add(1200);
numbers.Add(20300);
numbers.Add(39700);
numbers.Add(0);
numbers.Add(-1194861.7);
numbers.Add(2680);
numbers.Add(36977.82);
numbers.Add(155847.36);
numbers.Add(98933);
numbers.Add(141642);
numbers.Add(101600);
string numberSum = numbers.Sum(x => x).ToString();
Console.WriteLine("SUM : " + numberSum);
Console.ReadKey();

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,309 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 34,356 Reputation points Microsoft Vendor
    2023-05-25T05:40:07.5333333+00:00

    Hi @Samoj Bhattarai , Welcome to Microsoft Q&A.

    This is due to a problem with double precision data.

    Floating point numbers have limited precision and may introduce small rounding errors into calculations.

    In this case the sum of the numbers should be 0, but due to rounding errors you will get a very small non-zero value.

    Typically, we do some processing on the result.

    For example, as below, round the data to 2 decimal places and format it as "0.00".

    double sum = numbers.Sum(x => x);
    
    double roundedSum = Math.Round(sum, 2); // Round the sum to 2 decimal places
    
    string numberSum = roundedSum.ToString("0.00"); // Format the sum with two decimal places
    
    Console.WriteLine("SUM : " + numberSum);
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful