First, frequently asked questions
When using PHP for computing, you often encounter the problem of precision, the following two common examples:
1. Comparison of operations
The result of the following expression output is not 相等
:
<?php echo 2.01 - 0.01 == 2 ? ‘相等‘ : ‘不相等‘; // 不相等
2. Type conversion
The result of the following expression output is not 201
(if you want to output the result you want, you need to go to the string and then to int):
<?php$num = intval(2.01 * 100);var_dump($num); // int(200)
You may find it strange, however, that this is not a PHP bug, if you want to learn more about the two articles that you can refer to Brother Bird:
- About PHP floating-point numbers you should know (all ' bogus ' about the float in PHP)
- A FAQ for PHP floating-point numbers
Second, BC MATH
The BC Math series mathematical functions provided with PHP can solve the problem above. For mathematical calculations of arbitrary precision, BC Math provides a binary calculation of numbers that support any size and precision represented by a string, up to 2147483647-1 (or 0x7fffffff-1).
Use the functions provided by BC MATH to solve the above problem.
1. Comparison of operations
bccomp-compare two arbitrary-precision numbers:
<?php$num = bccomp(2.01 - 0.01, 2, 2); var_dump($num); // int(0)
Note: If two number equals returns 0, the left number compares to the number on the right to return 1, otherwise returns-1.
2. Type conversion
Bcmul-2 an arbitrary-precision numerical multiplication calculation:
<?php$num = bcmul(2.01, 100, 0);var_dump($num); // string(3) "201"var_dump(intval($num)); // int(201)
Note: Returns the result as a string type
Using the BC Math series math functions allows us to reduce errors, avoid unnecessary errors, and to see the details of parameters and the use of other functions, please refer to the official PHP documentation: http://php.net/manual/zh/book.bc.php
This article started in Mayanlong personal blog, Welcome to share, reproduced please indicate the source.
Mayanlong Personal Blog: http://www.mayanlong.com
Mayanlong personal Weibo: Http://weibo.com/imayanlong
Mayanlong GitHub Home: Https://github.com/yanlongma
PHP's BC Math series Mathematical functions