保留小數位數有很多種方法,常見的有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