2013-07-04 96 views
0

不要聽起來很愚蠢,但我想知道是否有一種非常簡單的方式從PHP中的數字中獲取百分比?PHP中的百分比

說我有70.40的數字,我想刪除15%。

到目前爲止,我有這樣的:

$discount = 15; 

$price = 70.40; 

$newPrice = $price - (($discount/100) * $price); 

但是,這似乎給了我各種隨機數。

有沒有更簡單的方法?

+0

你的代碼給了這個新的價格,持久。 :59.84。不是okey? –

+1

你寫錯了,因爲你寫的$ newPrice是$價格 - 70.40%的折扣(70.40%的15 = 10.56),但你想要15%的價格(相反),如果你只是改變它:$ newPrice = $價格 - (($價格/ 100)* $折扣);您的代碼將是確定 – Vladimir

回答

2

試試這個:

function apply_discount($price, $discount) { 
    $after_discount = $price - (($price/100) * $discount); 
    return $after_discount; 
} 

例如

echo apply_discount(200, 15); //170 
+0

應該在這種情況下的工作...... 「\t \t \t \t \t \t $價格= $ 2行[」 建議零售價「]; ..... $價格= apply_discount($價格,$ _ SESSION ['折扣']);」 ..... $從數據庫中帶來的價格和折扣正在存儲在一個會話 – Kevlar

+0

是的它是工作正常 – Dave

+0

@ Kevlar變量是變量:) – n1te

2
$discount = 15; 
$price = 70.40; 
$newPrice = $price * (100 - $discount)/100; 

如果你的$discount將是一個百分比(0和1之間),這將是:

$discount = 0.15; 
$price = 70.40; 
$newPrice = $price * (1 - $discount); 
0

70.40 * 0.15 = 10.56

,而0.15是15%

我想你可以做這樣的事情。

$discount = 0.15; 
$price = 70.40; 
$newPrice = $price - ($price * $discount);