2014-03-13 101 views
-5

實施例:如何格式化浮子到n位小數

22.453667 => 22.45

34.65355 => 34.65

+0

http://stackoverflow.com/questions/1619265/how-to-round-off-a-number-to-nearest-10 –

+1

http://www.php.net /manual/en/function.round.php – lafor

回答

1

使用number_format

$num = "22.469667"; 

// Without round 
echo number_format(floor($num*100)/100, 2, '.', ''); 
// output: 22.46 

echo "\n"; 

// With round 
echo number_format($num, 2, '.', ''); 
// output: 22.47 

http://codepad.org/BjGiEeVa

2

你應該使用PHP的round功能:

<?php 
echo round(3.4);   // 3 
echo round(3.5);   // 4 
echo round(3.6);   // 4 
echo round(3.6, 0);  // 4 
echo round(1.95583, 2); // 1.96 
echo round(1241757, -3); // 1242000 
echo round(5.045, 2); // 5.05 
echo round(5.055, 2); // 5.06 
?> 
+0

任何選項:echo round(3,4453); // 3,44 echo round(3,536); // 3,53 echo round(3,6783); // 3,37 – vino

0

number_format()比jogesh_pi判斷出這是容易得多。

只要做到:

$num = "22.453667"; 
echo number_format($num, 2); 

返回:22.45

它只是需要作爲第一個參數的號碼,然後你希望它四捨五入到小數點的數字。

$ num =「22.457667」;將返回22.46 $ num =「22」;將返回22.00

http://codepad.org/9zollLf5