1. Background description: Echo (10-9.8-0.2) in PHP code, will return a number similar to 0 but not 0, I see a lot of blogs also explain the reason why the calculation accuracy is lost, that is, binary saving these floating-point numbers will be distorted, can only approximate save.
2. Elicit the question: Then the question comes, how to avoid the display of the time to see the problem, such as avoiding the balance in your bank account can not always show that your amount is 0.000000001. Do you have any good solutions?
3. Take up method: I am just simple to use round to take the whole, but all the calculations I have to deal with the feeling is very troublesome, how to do?
Reply content:
1. Background description: Echo (10-9.8-0.2) in PHP code, will return a number similar to 0 but not 0, I see a lot of blogs also explain the reason why the calculation accuracy is lost, that is, binary saving these floating-point numbers will be distorted, can only approximate save.
2. Elicit the question: Then the question comes, how to avoid the display of the time to see the problem, such as avoiding the balance in your bank account can not always show that your amount is 0.000000001. Do you have any good solutions?
3. Take up method: I am just simple to use round to take the whole, but all the calculations I have to deal with the feeling is very troublesome, how to do?
The floating-point calculation in the program is approximate, and as a programmer, we should never expect the result to be accurate, so we need to figure out the accuracy requirement before the calculation. For example, even if the diameter of the solar system is calculated, when the π
precision is more than 10 bits behind the decimal point, the calculated RADIUS error is only a few centimeters.
In terms of amount, some languages have proprietary data types for amounts. Other languages have their own control, such as the amount of money generally only need to be accurate to the decimal 2
place. There is also a way to deal with the amount of money to save to points, for example, the 1
yuan is saved as a 100
point, the display of the time to process Narimoto to display, so when the calculation of the only need to involve an integer.
This kind of problem is too flood, search on the net can get the answer. It is unlikely that the result of the multiplier between floating-point numbers would be absolutely accurate.
You can take advantage of PHP's BC high-precision library of functions. The advantage of using this library is that you can control at least the exact number of digits and not get out of control. Please refer to the PHP manual.
echo bcsub(10-9.8-0.2,0);//0
http://php.net/manual/en/ref.bc.php