PHP的BCMath扩展相关函数介绍

发布时间:2020/05/24 作者:天马行空 阅读(1275)

关于PHP浮点数精度问题,我们先来看一段代码:

echo intval(0.58*100);//结果为57

echo intval((0.1 + 0.7) * 10);//结果为7


为什么会出现这样的问题呢?那是因为计算机内部对部分浮点数不能准确地用二进制表示,就像我们不能用十进制准确表示1/3=0.33333333333333一样。


所以,永远不要相信浮点数精确到了最后一位,如果涉及到需要用浮点数来进行运算,那么我们的php扩展bcmath就登场了。


bcmath是专门用来处理精度运算的一个扩展,我们日常用到的几个运算函数包括:


1、加法

bcadd ( string $left_operand , string $right_operand [, int $scale ] )

2、减法
bcsub ( string $left_operand , string $right_operand [, int $scale = int ] )

3、乘法
bcmul ( string $left_operand , string $right_operand [, int $scale = int ] )

4、除法
bcdiv ( string $left_operand , string $right_operand [, int $scale = int ] )

5、比较

如果两个数相等返回0,左边的数left_operand比较右边的数right_operand大返回1, 否则返回-1。

bccomp ( string $left_operand , string $right_operand [, int $scale = int ] )

6、取模
bcmod ( string $left_operand , string $modulus )

7、乘方
bcpow ( string $left_operand , string $right_operand [, int $scale ] )


$scale-此可选参数用于设置结果中小数点后的小数位数。


有了这个扩展,我们再也不用担心0.3不是0.3的问题了。

使用这些函数需要注意的是:设置的小数点后面如果有值会全部都舍弃掉,不会进行四舍五入

关键字php