If you use php +-*/to calculate the floating point number, you may encounter some calculation result errors, such as echo intval (0.58*100); 57 is printed instead of 58, this is actually a bug where binary at the bottom of the computer cannot accurately represent floating-point numbers.
It is cross-language. I also encountered this problem using python. Therefore, most languages provide precision computing class libraries or function libraries. For example, php has a high-precision BC function library. Below we will introduce some common high-precision BC functions.
The php BC high-precision function library includes: addition, comparison, division, subtraction, remainder, multiplication, and Npower. The default number of decimal places is configured and the square is obtained. These functions are useful when it comes to money computing, such as e-commerce price calculation.
/**
* Comparison of two high-precision numbers
*
* @ Access global
* @ Param float $ left
* @ Param float $ right
* @ Param int $ the number of decimal places accurate to scale
*
* @ Return int $ left =$ right returns 0 | $ left <$ right returns-1 | $ left> $ right returns 1
*/
Var_dump (bccomp ($ left = 4.45, $ right = 5.54, 2 ));
//-1
/**
* Adding two high-precision numbers
*
* @ Access global
* @ Param float $ left
* @ Param float $ right
* @ Param int $ the number of decimal places accurate to scale
*
* @ Return string
*/
Var_dump (bcadd ($ left = 1.0321456, $ right = 0.0243456, 2 ));
// 1.04
/**
* Two high-precision Subtraction
*
* @ Access global
* @ Param float $ left
* @ Param float $ right
* @ Param int $ the number of decimal places accurate to scale
*
* @ Return string
*/
Var_dump (bcsub ($ left = 1.0321456, $ right = 3.0123456, 2 ));
//-1.98
/**
* Division of two high-precision data sets
*
* @ Access global
* @ Param float $ left
* @ Param float $ right
* @ Param int $ the number of decimal places accurate to scale
*
* @ Return string
*/
Var_dump (bcdiv ($ left = 6, $ right = 5, 2 ));
// 1.20
/**
* Multiply two high-precision numbers
*
* @ Access global
* @ Param float $ left
* @ Param float $ right
* @ Param int $ the number of decimal places accurate to scale
*
* @ Return string
*/
Var_dump (bcmul ($ left = 3.1415926, $ right = 2.4569874566, 2 ));
// 7.71
/**
* Set the decimal point of the bc function.
*
* @ Access global
* @ Param int $ the number of decimal places accurate to scale
*
* @ Return void
*/
Bcscale (3 );
Var_dump (bcdiv ('123', '6. 123 '));
// 16.007
NOTE: For the set number of digits, the excess part is discarded rather than rounded up.