本文實例講述了PHP中round()函數對浮點數進行四捨五入的方法。分享給大家供大家參考。具體方法如下:
語法:round(x,prec)
參數 描述 x 可選,規定要捨入的數字. prec 可選,規定小數點後的位數.說明:返回將 x 根據指定精度 prec(十進制小數點後數字的數目)進行四捨五入的結果,prec 也可以是負數或零(默認值).
提示和注釋
注釋:php默認不能正確處理類似 "12,300.2" 的字符串.
注釋:prec 參數是在 php 4 中被引入的,實例代碼如下:
復制代碼 代碼如下:<?php
*/
echo round(3.4); //輸出3
echo "<br>";
echo round(3.5); //輸出4
echo "<br>";
echo round(3.6); //輸出4
echo "<br>";
echo round(3.6,0); //輸出4
echo "<br>";
echo round(1.95583,2); //輸出1.96
echo "<br>";
echo round(1241757,-3); //輸出1242000
echo "<br>";
echo round(4.045,2); //輸出4.05
echo "<br>";
echo round(4.055,2); //輸出4.06
//使用stdround函數代替php的round函數
?>
復制代碼 代碼如下:<?php
function stdround($num, $d=0)
{
return round($num + 0.0001 / pow(10, $d), $d);
}
echo "round(1.005,2)= ".round(1.005,2). "n ";
echo "round(1.015,2)= ".round(1.015,2). "n ";
echo "round(1.025,2)= ".round(1.025,2). "n ";
echo "round(1.035,2)= ".round(1.035,2). "n ";
echo "round(1.045,2)= ".round(1.045,2). "n ";
echo "round(1.055,2)= ".round(1.055,2). "n ";
echo "round(1.065,2)= ".round(1.065,2). "n ";
echo "round(1.075,2)= ".round(1.075,2). "n ";
echo "round(1.085,2)= ".round(1.085,2). "n ";
echo "round(1.095,2)= ".round(1.095,2). "n ";
echo "stdround(1.005,2)= ".stdround(1.005,2). "n ";
echo "stdround(1.015,2)= ".stdround(1.015,2). "n ";
echo "stdround(1.025,2)= ".stdround(1.025,2). "n ";
echo "stdround(1.035,2)= ".stdround(1.035,2). "n ";
echo "stdround(1.045,2)= ".stdround(1.045,2). "n ";
echo "stdround(1.055,2)= ".stdround(1.055,2). "n ";
echo "stdround(1.065,2)= ".stdround(1.065,2). "n ";
echo "stdround(1.075,2)= ".stdround(1.075,2). "n ";
echo "stdround(1.085,2)= ".stdround(1.085,2). "n ";
echo "stdround(1.095,2)= ".stdround(1.095,2). "n ";
$m=0.000000000000001;
echo "n ";
echo "round(1.005+{$m},2)= ".round(1.005+$m,2). "n ";
echo "round(1.015+{$m},2)= ".round(1.015+$m,2). "n ";
echo "round(1.025+{$m},2)= ".round(1.025+$m,2). "n ";
echo "round(1.035+{$m},2)= ".round(1.035+$m,2). "n ";
echo "round(1.045+{$m},2)= ".round(1.045+$m,2). "n ";
echo "round(1.055+{$m},2)= ".round(1.055+$m,2). "n ";
echo "round(1.065+{$m},2)= ".round(1.065+$m,2). "n ";
echo "round(1.075+{$m},2)= ".round(1.075+$m,2). "n ";
echo "round(1.085+{$m},2)= ".round(1.085+$m,2). "n ";
echo "round(1.095+{$m},2)= ".round(1.095+$m,2). "n ";
echo "round(1.005,2)= ".round(1.005,2). "n ";
echo "round(1.015,2)= ".round(1.015,2). "n ";
echo "round(1.025,2)= ".round(1.025,2). "n ";
echo "round(1.035,2)= ".round(1.035,2). "n ";
echo "round(1.045,2)= ".round(1.045,2). "n ";
echo "round(1.055,2)= ".round(1.055,2). "n ";
echo "round(1.065,2)= ".round(1.065,2). "n ";
echo "round(1.075,2)= ".round(1.075,2). "n ";
echo "round(1.085,2)= ".round(1.085,2). "n ";
echo "round(1.095,2)= ".round(1.095,2). "n ";
?>
希望本文所述對大家的PHP程序設計有所幫助。