I have a whole bunch of percentages stored as XX% (e.g. 12%, 50%, etc..) I need to remove the percentage sign and then multiply the percent against another variable thats just a number (e.g. 1000, 12000) and then output the result. Is there a simple way to strip the percentage sign and then calculate the output with PHP? Or should I consider some sort of JS solution?
views:
61answers:
6
+4
A:
You could use rtrim()
:
$value = ((int) rtrim('12%', '%')) * 1000';
Edit
You don't strictly need to call rtrim() , as it casts to an int ok with the percentage sign. It is probably cleaner to strip it though.
var_dump (12 === (int) '12%');
//output: bool(true)
Tom Haigh
2010-04-19 16:34:56
I thought casting it would work. Now I don't have to add another duplicate answer. I do wonder which is faster - trim, cast, string manipulation or grep.
Simurr
2010-04-19 16:57:06
A:
You can use str_replace. You can also pass an array of subjects into str_replace to have them all replaced.
<?php
$number = str_replace("%", "", $percentage);
$result = $number * $other_var;
print $result;
?>
Ty W
2010-04-19 16:35:18
+1
A:
Try this:
$number = str_replace('%', '', '100%');
$result = intval($number) * 5000; // or whatever number
echo $result;
Sarfraz
2010-04-19 16:35:56
+1
A:
If you use trim() or str_replace() in PHP you can remove the percent sign. Then, you should be able to multiply the resulting number (php is weakly typed after all).
<?php
$number = str_replace("%", "", $percentString);
$newNumber = ((int) $number) * 1000;
echo $newNumber;
?>
zipcodeman
2010-04-19 16:36:47
+1
A:
You can make use of preg_replace_callback as:
$input = '12%, 50%';
$input = preg_replace_callback("|(\d+)%|","replace_precent",$input);
echo $input; // 12000, 50000
function replace_precent($matches) {
return $matches[1] * 1000;
}
codaddict
2010-04-19 16:38:54
A:
<?php
$input=array('15%','50%','10.99%','21.5%');
$multiplier=1000;
foreach($input as $n){
$z=floatval($n)*$multiplier;
print("$z<br>");
}
?>
zaf
2010-04-19 16:51:10