php中, 进行浮点数的加减乘除等运算时, 直接用 +-*/
会造成精度丢失,
$a = 0.1; $b = 0.7; $c = intval(($a + $b) * 10); echo $c; // 输出结果: 7
$a = 100; $b = 99.97; $c = $a - $b; echo $c; // 输出结果: 70.030000000000001
$a = 0.58; $b = 100; $c = intval($a * $b); echo $c; // 输出结果: 57
$a = 0.7; $b = 0.1; $c = intval($a / $b); echo $c; // 输出结果: 6
这个时候,可以安装bcmath扩展,使用bc函数.
$a = 0.1; $b = 0.7; $c = intval(bcadd($a , $b,1) * 10); echo $c."\r\n"; // 输出结果: 8
$a = 100; $b = 99.97; $c = bcsub($a , $b,2); echo $c."\r\n"; // 输出结果: 0.03
$a = 0.58; $b = 100; $c = intval(bcmul($a , $b)); echo $c."\r\n"; // 输出结果: 58
$a = 0.7; $b = 0.1; $c = intval(bcdiv($a , $b)); echo $c; // 输出结果: 7
本文为Larwas原创文章,转载无需和我联系,但请注明来自larwas博客 https://larwas.com
最新评论