convert these strings to number - php

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;

Related

Split a string using foreach?

Is it possible to split a string using foreach?
For example my string value is 10
using foreach echos 1,
then echo 2,
then echo 3,
and so on to till it reach the string value.
Yes you can but looking at what you try to achieve, you really don't need to split instead you are trying to increment using loop till the string value reached. In PHP you can cast string to integer and by default PHP will do that for you if you are trying to perform + - * % / operations.
Using Foreach
$string = '10';
$numbers = range(1, $string);
foreach($numbers as $number){
echo $number;
}
Using For
$string = '10';
for($i = 1; $i <= $string; $i++){
echo $i;
}
If splitting string is what your objective, you can use str_split() function and loop like the above foreach()

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");

PHP - Adding up an array of numbers?

I have a PHP script that returns an array of numbers:
$fh = fopen ("./files/".$file, r);
$filedata= explode('|', fgets($fh));
echo $filedata[5];
result:
0.23387718200684
3.6163940429688
0.030826568603516
Is there a way to get the script to return results added up as just one number?
echo array_sum($filedata);
I think that should do the trick.
Take a look here for further information. array_sum just sums up all the values in an array.
EDIT
The above example would work if your array was a flat array of integers, decimals etc. The following is how you would sum up a 2 dimensional array where the value you want to sum is at index position 5:
var $sum = 0;
foreach($filedata as $dataElement) {
$sum += $dataElement[5];
}
echo $sum;
The above code assume that $filedata is an array of array's, each array in filedata has a value at index 5 that can be summed up... Is that more along the lines of what you need?
You could use array_sum:
echo array_sum($filedata);
Not working?
As might be your case $filedata[5] actually contains a string with newlines and numbers. In this case you need some extra code. Important is the line endings - these can be different depending on your operating system / file.
$sum = 0;
$sLineEnding = "\r\n";
foreach($filedata as $data)
{
$parts = explode($sLineEnding, $data);
$sum += array_sum($parts);
}
echo $sum;
As I see in your code, you are executing it in command line and you do echo $filedata[5] an you get different lines, this is because you are not paying attention to '\n' character, so what you need is to change that character somehow...
there are different ways... In this example I'm changing the "\n" for " " simple space
$fh = fopen ("./files/".$file, r);
$filedata= explode('|', fgets($fh));
// if "\n" is not working try '\n'
// One way
echo str_replace(" ","\n",$filedata[5]);
// Another way
echo implode(" ", explode("\n", $filedata[5]));

Leading zeroes in PHP

I would like to present a list from 0 to 59 with the numbers 0 to 9 having a leading zero. This is my code, but it doesn't work so far. What is the solution?
for ($i=0; $i<60; $i++){
if ($i< 10){
sprintf("%0d",$i);
}
array_push($this->minutes, $i);
}
Using %02d is much shorter and will pad the string only when necessary:
for($i=0; $i<60; $i++){
array_push($this->minutes,sprintf("%02d",$i));
}
You are not assigning the result of sprintf to any variable.
Try
$padded = sprintf("%0d", $i);
array_push($this->minutes, $padded);
Note that sprintf does not do anything to $i. It just generates a string using $i but does not modify it.
EDIT: also, if you use %02d you do not need the if
Try this...
for ($i = 0; $i < 60; $i++) {
if ($i < 10) {
array_push($this->minutes, sprintf("%0d", $i));
}
array_push($this->minutes, $i);
}
You are ignoring the returned value of sprintf, instead of pushing it into your array...
important: The method you are using will result in some items in your array being strings, and some being integers. This might not matter, but might bite you on the arse if you are not expecting it...
Use str_pad:
for($i=0; $i<60; $i++){
str_pad($i, 2, "0", STR_PAD_LEFT)
}
I like the offered solutions, but I wanted to do it without deliberate for/foreach loops. So, here are three solutions (subtle variations):
Using array_map() with a designed callback function
$array = array_map(custom_sprintf, range(0,59));
//print_r($array);
function custom_sprintf($s) {
return sprintf("%02d", $s);
}
Using array_walk() with an inline create_function() call
$array = range(0,59);
array_walk($array, create_function('&$v', '$v = sprintf("%02d", $v);'));
// print_r($array);
Using array_map() and create_function() for a little code golf magic
$array = array_map(create_function('&$v', 'return sprintf("%02d", $v);'), range(0,59));

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

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>");
}
?>

Categories