If you use PHP +-*/to calculate the floating-point number, you may encounter some errors in the calculation results, such as Echo Intval (0.58*100), will print 57, instead of 58, this is actually the bottom binary system of the computer can not accurately represent a floating point number of a bug, is a cross-language, I also encountered this problem with Python. So basically most of the language provides a precise calculation of the class library or function library, such as PHP has a BC high-precision function library, the following describes some of the commonly used BC high-precision function.
PHP BC High-Accuracy library contains: Add, compare, divide, subtract, balance, multiply, n-squared, configure the default number of decimal points, squared. These functions are useful when it comes to money calculations, such as the price calculation of e-commerce.
/** * Two high-precision number comparison * * @access global * @param float $left * @param float $right * @param int $scale The exact number of decimal places * * @ return int $left = = $right return 0 | $left < $right back-1 | $left > $right return 1 */var_dump (Bccomp ($left =4.45, $right = 5.54, 2))//-1/** * Two high-precision numbers added * * @access global * @par AM Float $left * @param float $right * @param int $scale The exact number of decimal places * * @return string */var_dump (Bcadd ($left =1.0321 456, $right = 0.0243456, 2));//1.04/** * Two high-precision number subtraction * * @access global * @param float $left * @param float $right * @param int $scale The exact number of decimal places * * @return string */var_dump (Bcsub ($left =1.0321456, $right = 3.0123456, 2));//-1.98/** * Divide between two high-precision numbers * * @access global * @param float $left * @param float $right * @param int $scale The exact number of decimal places * * @retu RN String */var_dump (Bcdiv ($left =6, $right = 5, 2));//1.20/** * Two high-precision numbers multiplied * * @access global * @param float $left * @param float $right * @param int $scale The exact number of decimal places * * @return string */var_dump (bcmUL ($left =3.1415926, $right = 2.4569874566, 2))//7.71/** * Set the number of decimal places for the BC function * * @access global * @param int $scale exact decimal Number of points * * @return void */Bcscale (3); Var_dump (Bcdiv (' 105 ', ' 6.55957 ')); 16.007 Note: About the number of bits set, the excess is discarded, not rounded
PHP floating point calculation problem