2012-02-19 85 views
3

說我有PHP刪除結尾零?

$number = .20 

當我去運行腳本,PHP自動刪除零,只留下0.2。這怎麼解決?

我知道.2和.20是相同的,但是我使用這個數字的時候,我需要零。

回答

3

唯一想我能想到的要求後0時顯示數字。 .20可以打印如下:

// The number to display 
$n = .2; 

// The number of decimal places 
$places = 2; 

// Print the number to the desired precision. 
echo number_format($n, $places) 
+0

謝謝!這工作! – Alec 2012-02-19 05:40:19

+0

如果答案解決了您的問題,請將其標記爲接受的答案。 – 2012-03-22 02:01:31

2

你可以把它串

$number = '.20'; 
0

0.20是文字的浮動。分析完成後,它將轉換爲floating point。你可以用兩位小數後用格式化:

sprintf("%.2f\n", $number); 

但是,如果你不使用它作爲一個數可言,邁克是正確的,你應該只把它作爲一個字符串。

+0

我用one @ erm410表示。值改變了,所以這就是爲什麼我不能像Mike說的那樣使用一個字符串。 – Alec 2012-02-19 05:41:21

3
 

$num = "0.20"; 
echo "Num is:".$num; 

//OR 
$num = number_format(0.20, 2); 
echo "Num is:".$num; 
 
1

你可以通過格式化數字:

$num_decimal_places = 2; // This will give .20 
$formatted = number_format($number, $num_decimal_places, '.', '');