保留小数位数有很多种方法,常见的有round(),bcadd(),number_format(),sprintf()四种方法。其中round()的小数位数并不是那么可靠,它在值是整数的时候,会没有小数位数。
$str = ‘5.0000‘;
$strRound = round($str,2);
echo ‘round: ‘.$strRound;
echo ‘<br/>‘;
$strBcadd = bcadd($str,0,1);
echo ‘bcadd: ‘.$strBcadd;
echo ‘<br/>‘;
$strNubmerFormat = number_format($str,2);
echo ‘number_format: ‘.$strNubmerFormat;
echo ‘<br/>‘;
$strSprintf = sprintf(‘%.2f‘,$str);
echo ‘sprintf: ‘.$strSprintf;
echo ‘<br/>‘;
输出
round: 5
bcadd: 5.0
number_format: 5.00
sprintf: 5.00