2015-03-31 44 views
0

我需要使這個打印數字有兩個小數點,我相信我使用這段代碼int $decimals = 0,但我不知道我需要添加它的位置。

這裏是我的代碼:

<?php 
    $tempPrice = str_replace(',',"", $price); //gets rid of "," 
    $tempPrice = substr($tempPrice,2); //removes currency from the front 
    $tempPrice = floatval($tempPrice); //converts to double from string 

    if($tempPrice > 1000) 
    { 
    echo '£' . round(($tempPrice*0.038), 2) . ' per month'; 
    } 
    else 
    { 
    echo 'Lease to buy price not available on this product'; 
    } 
?> 

感謝

+0

'number_format' – 2015-03-31 09:36:01

回答

0

您可以使用money_format()PHP函數。 http://php.net/money_format

例如,在你的情況

<?php 
    $tempPrice = str_replace(',',"", $price); //gets rid of "," 
    $tempPrice = substr($tempPrice,2); //removes currency from the front 
    $tempPrice = floatval($tempPrice); //converts to double from string 
    // set international format for the en_GB locale 
    setlocale(LC_MONETARY, 'en_GB');  
    if($tempPrice > 1000) 
    { 
    echo money_format('%i', $tempPrice) . " per month";// output->"GBP 1,234.56 per month" 
    } 
    else 
    { 
    echo 'Lease to buy price not available on this product'; 
    } 
?> 

除了可以只使用PHP number_format()http://php.net/number_format在$ tempPrice

echo "£ ". number_format($tempPrice) . " per month"; 

默認number_format()用英語書寫。你可以設置自己的小數點數,小數點setarator和千位分隔符

echo "£ ". number_format($tempPrice, 2, ".", ",") . " per month"; // for $tempPrice=1203.52 output will be "£ 1,203.56 per month" 
+0

嗨,彼得感謝您的幫助。第一個例子打印英鎊,有沒有辦法改變這個£?用number_format替代我應該改變'。圓'到'。 number_format'? – 2015-03-31 10:12:27

+0

您的問題的第一部分在此之前回答http://stackoverflow.com/questions/9019337/php-money-format-%C2%A3-sign-not-gbp。在第二部分...是的,改變它,但檢查number_format函數將其設置爲您的需要。 – 2015-04-02 06:35:12