用PHP的+ - * /(四则运算) 计算浮点数的时候,可能会遇到一些计算结果错误的问题,所以基本上大部分语言都提供了精准计算的类库或函数库,比如PHP有BC高精确度函数库
bc是Binary Calculator的缩写。bc*函数的参数都是操作数加上一个可选的 [int scale],比如string bcadd(string $left_operand, string $right_operand[, int $scale]),如果scale没有提供,就用bcscale的缺省值。这里大数直接用一个由0-9组成的string表示,计算结果返回的也是一个 string。
-
bcadd —— 2个任意精度数字的加法计算
string bcadd ( string $left_operand , string $right_operand [, int $scale ] )
左操作数和右操作数求和<?php $a = '1.234' ; $b = '5' ; echo bcadd ( $a , $b ); // 6 echo bcadd ( $a , $b , 4 ); // 6.2340 ?>
-
bccomp —— 比较两个任意精度的数字
bccomp ( string $left_operand , string $right_operand [, int $scale = int ] ) : int
把right_operand和left_operand作比较, 并且返回一个整数的结果.<?php echo bccomp('1', '2') . "\n"; // -1 echo bccomp('1.00001', '1', 3); // 0 echo bccomp('1.00001', '1', 5); // 1 ?>
-
bcdiv —— 2个任意精度的数字除法计算
bcdiv ( string $left_operand , string $right_operand [, int $scale = int ] ) : string
左操作数除以右操作数<?php echo bcdiv('105', '6.55957', 3); // 16.007 ?>
-
bcmod —— 对一个任意精度数字取模
bcmod ( string $left_operand , string $modulus ) : string
对左操作数使用系数取模<?php echo bcmod('4', '2'); // 0 echo bcmod('2', '4'); // 2 ?>
-
bcmul —— 2个任意精度数字乘法计算
bcmul ( string $left_operand , string $right_operand [, int $scale = int ] ) : string
左操作数乘以右操作数<?php echo bcmul('1.34747474747', '35', 3); // 47.161 echo bcmul('2', '4'); // 8 ?>
-
bcpow —— 任意精度数字的乘方
bcpow ( string $left_operand , string $right_operand [, int $scale ] ) : string
左操作数的右操作数次方运算.<?php echo bcpow('4.2', '3', 2); // 74.08 ?>
-
bcpowmod —— 将任意精度数提高到另一个,降低指定的模数
bcpowmod ( string $base , string $exponent , string $modulus [, int $scale = 0 ] ) : string
使用快速幂运算方法将基础增加到关于模数模数的功率指数。注释:
由于该方法使用了模运算,所以非正整数的数字可能会得到意外的结果。<?php $a = bcpowmod($x, $y, $mod); $b = bcmod(bcpow($x, $y), $mod); // $a and $b are equal to each other. ?>
-
bcscale —— 设置所有bc数学函数的默认小数点保留位数
bcscale ( int $scale ) : bool
设置所有bc数学函数的未设定情况下得小数点保留位数.<?php // default scale : 3 bcscale(3); echo bcdiv('105', '6.55957'); // 16.007 // this is the same without bcscale() echo bcdiv('105', '6.55957', 3); // 16.007 ?>
-
bcsqrt —— 任意精度数字的二次方根
bcsqrt ( string $operand [, int $scale ] ) : string
返回操作数的二次方根.<?php echo bcsqrt('2', 3); // 1.414 ?>
-
bcsub — 2个任意精度数字的减法
bcsub ( string $left_operand , string $right_operand [, int $scale = int ] ) : string
左操作数减去右操作数.<?php $a = '1.234'; $b = '5'; echo bcsub($a, $b); // -3 echo bcsub($a, $b, 4); // -3.7660 ?>