tags:

views:

61

answers:

6

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?

+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
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
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
+1  A: 

Try this:

$number = str_replace('%', '', '100%');
$result = intval($number) * 5000; // or whatever number
echo $result;
Sarfraz
+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
+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
replacing the percent sign would be * 100 no?
SeanJA
@SeanJA: Right :) but the OP mentions in the question `1000, 12000`
codaddict
A: 
<?php

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

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

?>
zaf