Remove last character from a variable and then multiply against another variable - php

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?

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)

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;
}

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

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;
?>

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;
?>

<?php
$input=array('15%','50%','10.99%','21.5%');
$multiplier=1000;
foreach($input as $n){
$z=floatval($n)*$multiplier;
print("$z<br>");
}
?>

Related

How to convert decimals correctly after calculation [duplicate]

This question already has answers here:
Why is PHP printing my number in scientific notation, when I specified it as .000021?
(7 answers)
Closed 10 months ago.
I have the below problem, how to make it appear 0.00004 as string after multiplication?
$v = -0.00004;
$v = $v * -1;
echo $v; // 4.0E-5
Long story
As a result I need to save into MySQL database but no problem with that because I use below query:
$sql_insert = $conn->prepare("insert into tbl_transaction (amount) values ($v)");
However when I output to my HTML it showing 4.0E-5. I tried to use number_format but in some cases the decimals will go far more than this so it is not a choice.
Try this.
echo sprintf('%f', $v);
Or:
$b = sprintf('%f', $v);
echo $b;
You can try as below.
$v = -0.00004;
$v = $v * -1;
echo number_format($v, 5);
Hope this will help.
After formatting the number with the desired precision you need to strip the trailing zeros.
This should do the trick:
$v = -0.00004;
$v = number_format($v * -1, 20);
print rtrim($v, 0);
If you var_dump($v) after the first assignment, you'll see that the "problem" is NOT the calculation.
$v = -0.00004;
var_dump($v); //float(-4.0E-5)
number_format() can be used to return a formatted version of your value. You can get the length of the string value, and pass that to number_format.
var_dump(number_format($v,strlen(strval($v)))); // string(10) "-0.0000400"
So, your code would be:
$v = -0.00004;
$v = $v * -1;
$v = number_format($v,strlen(strval($v)));
echo $v //0.000040
You don't need to use number_format until you're ready to display the value because the exponential number is the same value as the formatted / decimal number.

convert these strings to number

using php. I have the following number
4,564,454
454,454,454
54.54
65.43
I want to convert these into number for calculating. How can I do it? Right now, the type of these number is string.
Note: the comma is not a separate of a number, it is a notion to make a number nicer. I got this format from the ajax request, I cant change the format though. So, I have to use it.
Thanks
$var = floatval(str_replace(",", "", "454,454,454"));
$a='4,5,4';
$ab= explode(',', $a);
foreach ($ab as $b)
{
$sum+=$b; //perform your calculation
}
echo $sum;
First you need to remove ,(comma) from your string as below :
$str=str_replace(",", "", "454,454,454");
Then converting in numeric:
$int = (int)$str;
or
$int=intval($str);
now do your calculation using $int variable.
try this code
$str = '4,564,454';
$str2 = '454,454,454';
$str3= '54.54';
$str4= '65.43';
$sum=0;
$sum += array_sum(explode(',',$str));
$sum += array_sum(explode(',',$str2));
$sum += $str3;
$sum += $str4;
echo $sum;

How to convert Exponentials to Decimals in PHP

I have a string like this:
9.018E-14
Now I want to convert to this to the normal decimal numbers.
MyGeekPal has a nice article on it.
Code:
<?php
$total_time = 2.8848648071289E-5;
echo exp2dec($total_time);
function exp2dec($number) {
preg_match('/(.*)E-(.*)/', str_replace(".", "", $number), $matches);
$num = "0.";
while ($matches[2] > 0) {
$num .= "0";
$matches[2]--;
}
return $num . $matches[1];
}
?>
If your input is a float
If you have $number = 0.00023459 then printing this value in PHP will probably result in this exponential format. It doesn't mean the variable is stored that way; it's just an output artefact.
Use printf to work around this and gain control over your numeric output.
If your input is a string
Why the complexity?
$matches = Array();
if (preg_match('/(.*)E-(.*)/', $number, $matches)) {
$number = $matches[1] * pow(10, -1*$matches[2]);
}
Though you can tighten up the regex a bit:
$matches = Array();
if (preg_match('/(\d+(?:\.\d+)?)E(-?\d+)/i', $number, $matches)) {
$number = (float)$matches[1] * pow(10, (int)$matches[2]);
}
Live demo
EDIT: Here is some PHP magic:
$stringval = "12e-3";
$numericval = 0 + $stringval;
From the PHP docs:
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
If you need a more flexible format (e.g. extract four numbers from the same string), use sscanf like this:
$stringval = "12e-3";
$numericval = sscanf($stringval, "%f")[0];
echo $numericval;

php number operations

I have problems to get my percent counter function to get it work with English money format
function calc_proc($price, $savings) {
$old_price = $price + $savings;
return (number_format($savings / ($old_price/100)));
}
because of the commas I'm getting bad values
Is english money format something like this: 253,17?
If yes, then simply do:
str_replace(',', '.', $value);
Then you're safe.
First of all you don't have to use strings in financial calculations but if you still have to use, you should replace commas with dots. For example,
$a = '1,5';
$b = '2,1';
echo $a + $b; //result 3
// you can avoid this, by replacing comma:
$a = str_replace(',', '.', $a);
//same for $b
Another solution could be setting locale but you'd have issues with dots after that.
In your function it'll look like this:
function calc_proc($price, $savings) {
$price = str_replace(',', '.', $price);
$savings = str_replace(',', '.', $savings);
$old_price = (float)$price + (float)$savings;
return (number_format($savings / ($old_price/100)));
}
The PHP number_format() function without parameters return english format with comma. You should instead use:
return round($savings / ($old_price/100), 0);
and make sure $old_price cant be 0
function percent($price, $savings) {
$count1 = str_replace(',', '.', $price)/ $savings;
$count2 = $count1 * 100;
$count = number_format($count2, 0);
return $count;
}
Try setlocale(constant, location) at the beginning of your script. In your case:
setlocale(LC_ALL,"En-Us");

How to insert a string inside another string?

Just looked at function
str_pad($input, $pad_length, $pad_str, [STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH])
which helps to pad some string on left, right or on both sides of a given input.
Is there any php function which I can use to insert a string inside an input string?
for example ..
$input = "abcdef";
$pad_str = "#";
so if I give insert index 3, it inserts "#" after first 3 left most characters and $input becomes "abc#def".
thanks
You're looking for a string insert, not a padding.
Padding makes a string a set length, if it's not already at that length, so if you were to give a pad length 3 to "abcdef", well it's already at 3, so nothing should happen.
Try:
$newstring = substr_replace($orig_string, $insert_string, $position, 0);
PHP manual on substr_replace
you need:
substr($input, 0, 3).$pad_str.substr($input, 3)
Bah, I misread the question. You want a single insert, not insert every X characters. Sorry.
I'll leave it here so it's not wasted.
You can use regular expressions and some calculation to get your desired result (you probably could make it with pure regexp, but that would be more complex and less readable)
vinko#mithril:~$ more re.php
<?php
$test1 = "123123123";
$test2 = "12312";
echo puteveryXcharacters($a,"#",3);
echo "\n";
echo puteveryXcharacters($b,"#",3);
echo "\n";
echo puteveryXcharacters($b,"$",3);
echo "\n";
function puteveryXcharacters($str,$wha,$cnt) {
$strip = false;
if (strlen($str) % $cnt == 0) {
$strip = true;
}
$tmp = preg_replace('/(.{'.$cnt.'})/',"$1$wha", $str);
if ($strip) {
$tmp = substr($tmp,0,-1);
}
return $tmp;
}
?>
vinko#mithril:~$ php re.php
123#123#123
123#12
123$12

Categories