2010-04-19 66 views
0

我有一大堆存儲爲XX%的百分比(例如12%,50%等)。我需要刪除百分比符號,然後乘以百分比與另一個只是數字的變量(例如1000,12000)相比較,然後輸出結果。有沒有簡單的方法去除百分比符號,然後用PHP計算輸出?或者我應該考慮某種JS解決方案?從變量中刪除最後一個字符,然後乘以另一個變量

回答

1

您可以使用preg_replace_callback爲:

$input = '12%, 50%'; 
$input = preg_replace_callback("|(\d+)%|","replace_precent",$input); 

echo $input; // 12000, 50000 

function replace_precent($matches) { 
    return $matches[1] * 1000; 
} 
+0

替換百分號將是* 100否? – SeanJA 2010-04-19 16:41:57

+0

@SeanJA:對:)但OP在提問'1000,12000'中提到 – codaddict 2010-04-19 16:43:09

4

你可以使用rtrim()

$value = ((int) rtrim('12%', '%')) * 1000'; 

編輯

你不嚴格需要調用RTRIM(),因爲它轉換爲int確定與百分號。剝離它可能更乾淨。

var_dump (12 === (int) '12%'); 
//output: bool(true) 
+0

我想鑄造它會工作。現在我不必添加另一個重複的答案。我不知道哪個更快 - 修剪,投射,字符串操作或grep。 – Simurr 2010-04-19 16:57:06

0

您可以使用str_replace。您也可以將一組主題傳遞給str_replace,以便全部替換它們。

<?php 
    $number = str_replace("%", "", $percentage); 
    $result = $number * $other_var; 
    print $result; 
?> 
1

試試這個:

$number = str_replace('%', '', '100%'); 
$result = intval($number) * 5000; // or whatever number 
echo $result; 
1

如果在PHP中使用trim()str_replace()可以去掉百分號。然後,你應該能夠將結果數字相乘(畢竟php是弱類型的)。

<?php 
    $number = str_replace("%", "", $percentString); 
    $newNumber = ((int) $number) * 1000; 
    echo $newNumber; 
?> 
0
<?php 

$input=array('15%','50%','10.99%','21.5%'); 
$multiplier=1000; 

foreach($input as $n){ 
    $z=floatval($n)*$multiplier; 
    print("$z<br>"); 
} 

?> 
相關問題