SoFunction
Updated on 2025-03-07

Solutions to the error of adding two Double types in the program

Today, I discovered a strange phenomenon in the system I made: the sum of several Double type data is always a few cents less than the correct value. I thought there was a problem with the calculation method in the program, but after checking many places, I still couldn't find out what the problem was. Finally, I simply split the calculation method one by one, and the simplest step was to add two specific values, but the final result was still wrong. For example, now the simplest step:

Copy the codeThe code is as follows:

double n = 171.6;
double m = 28.17;
double k = n + m;

In theory, the value of k should be 199.77, but in fact, what I get is 199.769999999999999999999998.

Our system has 4 decimal places reserved in our system, which can be rounded to 199.77. However, because the amount of the total is the sum of dozens or even hundreds of data, the above error may occur when every two numbers are added, so the final result has an error of nearly 0.7, and even rounding it will be useless.

I checked the relevant information online and felt that the explanation of this post in the CSDN forum is quite detailed: /topics/300023952, which means that the calculation is caused by the conversion of the division during calculation (see reply on the 8th floor), all precision types have this problem in almost all languages. The more effective solution is to use BigDecimal (see reply on the 14th floor), but I personally think that BigDecimal solution is too troublesome, at least for my system. It is better to convert the string once after each addition to retain the valid decimal places. For example, the above statement can be rewritten as:

Copy the codeThe code is as follows:

double n = 171.6;
double m = 28.17;
//double k = n + m;
String kn = (n + m).ToString("N4");    //Retain 4 decimal places
double k = (kn);

In other words, at the String kn step, the error has been adjusted, and the k value obtained is correct. In this way, the error is processed every time the sum is added. No matter how many data you have to calculate, there is no need to worry about the error being too large.

    Of course, it is best to make this processing method a common method, specifically used to handle the addition of two numbers.