There will be some error in the result of double addition (subtraction)

There will be some error in the result of double addition (subtraction)

Prerequisite introduction

      Today, when debugging the code, I found an interesting problem of subtracting double data, 148163.1-82692.09 Everyone guesses what the result is equal to, after debugging, the final result is 5471.010000000009.

Isn’t it weird? The mystery of this will be explained below!

Reason explanation

     Double belongs to floating binary point types, that is to say, when adding and subtracting double values, the value will be converted into a binary value such as 10001.10010110011 and then added and subtracted, but it is converted into binary code. At that time, the number of digits stored in the decimal part will be insufficient, that is, the infinite loop decimal, which is the main reason for the slight gap.

Solution

1. Take only the digits that need to be used:

 Don't worry about the number of digits behind the decimal point, but this method is not very good.

 2. Use Decimal type:

With Decimal, the above problems will not occur, and the decimal value can be calculated accurately. The range of knowledge Decimal is smaller than that of double, and it is enough in general .

 The Decimal type has 28 effective digits, and the double type has 16 bits, so the Decimal type can represent more accurate floating-point numbers than the Double type. Related knowledge can refer to the link below.

Decimal, double, float in c#

summary

1. It is better to use 1.02-1.01==double.MinValue to judge when comparing the size of double type values.

2. Use the double type for addition and subtraction to see if you can use the Decimal type for calculation

Reference: https://cloud.tencent.com/developer/article/1014591 Double addition (subtraction) results will have some errors-Cloud + Community-Tencent Cloud