PHP Math issue with negatives [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP negatives keep adding
I have this code here....
$remaining = 0;
foreach($array as $value=>$row){
$remaining = $remaining + $row['remainingbalance'];
}
What its doing is that it is going through all the remaining balances in the array which are -51.75 and -17.85 with the code above I get -69.60 which is correct. But I am wondering how when its two negatives if they could subtract? Is that possible?
I tried this
$remaining = 0;
foreach($clientArrayInvoice as $value=>$row){
$remaining = $remaining + abs($row['remainingbalance']);
}
but it gives me 69.60 without the negative.
Anyone got any ideas?
my goal is to take -51.75 and -17.85 and come up with -33.90 only when its a negative to do subtract. otherwise add

Whenever you add a negative number, you actually subtract the positive value (and the other way around).
So 0 + (-16) = 0 - 16 = -16.
When you call abs() you calculate something completely different.

Related

Question about calculating Average in PHP [duplicate]

This question already has answers here:
How to calculate correctly in php?
(6 answers)
Closed 1 year ago.
I am a newbie learning PHP and i am trying to find average of 3 numbers but not getting the correct answer. I don't know where i am going wrong.
function percentage($math,$eng,$sc){
$s = $math+$eng+$sc / 3 ;
return $s;
}
$p = percentage(10,20,30);
echo $p;
I am getting the ansewer as 40 whereas i am supposed to get 20. Kindly check if there is any error.
Return value is right. Check operators precedence.
If you want 20 as return value code is:
$s = ($math+$eng+$sc) / 3 ;
You forgot to use parentheses:
$s = ($math+$eng+$sc) / 3 ;
All things together:
function percentage($math,$eng,$sc){
$s = ($math+$eng+$sc) / 3 ;
return $s;
}
echo percentage(10,20,30);

Ho do I output integers with leading zeros in PHP? [duplicate]

This question already has answers here:
Formatting a number with leading zeros in PHP [duplicate]
(11 answers)
Closed 3 years ago.
I need a little help with some PHP code. I looked at the examples for doing this with JavaScript and used that as the basis for a PHP implementation. Two issues I haven't be able to resolve. I still get a leading 1 at the start of the string. I also get fewer zeros than specified once the values have trailing zeros (i.e 10, 20, etc).
$num = 2;
$numZeros = 5;
function listRiskNumber($num, $numZeros) {
$n = abs($num);
$zeros = max(0, $numZeros - strlen(floor(json_encode($n))));
$zeroString = substr((pow(10,$zeros)),0,5);
if( $num < 0 ) {
$zeroString = '-' + $zeroString;
}
return $zeroString + $n;
}
$row = listRiskNumber($num, $numZeros);
echo $row;
I want to turn the leading 1 into a zero, and ensure trailing zeros don't get cut off. Any help would be greatly appreciated.
sprintf("%08d", $value);
Solved the problem. Thanks all for the quick answers.

2 exact values not equal to each other within if statement in php [duplicate]

This question already has answers here:
Compare floats in php
(17 answers)
Closed 6 years ago.
I have been getting information from the database which adds the cost of each item in a table.
Every is working 100% apart from when the cost is equal to a curtain sum it does not become equal, it is always greater.
For example if 30.02 == 30.02 it should become true, but its saying it is greater than.
Basically I have a foreach loop which is getting the cost of each invoice from an array which goes like this:
$i_array = array('2','3','4','5');
$i_total = 0;
$a_total = 0;
foreach($i_array as $i){ $i_total += floatval($i); }
Then I have a little bit of code which checks all invoices and if there are any it then adds them like this:
$query = $pdo->prepare("SELECT cost FROM tablename WHERE id=id");
$query->execute(array(':id' => $_GET['id']));
while($fetch = $query->fetch()){
$a_total += floatval($fetch['cost']);
}
From there I do a simple if statement:
if($i_total > $a_total){ echo 'Too Much'; }
Now the problem is if i_total is lets say 30.02 and lets say the a_total is also 30.02 then it should be equal and it should not echo Too Much but its still echos Too Much.
If the i_total is lower or greater it is fine, just when its equal.
Anyone could shed some light on this it would be greatful :)
You could try with number_format(). Then you are comparing string values instead of float.

How to get time sum [duplicate]

This question already has answers here:
PHP add up two time variables
(7 answers)
Closed 8 years ago.
I need to get time sum in normal format, im trying like this
$total_extra += $arr['extra'][$i]
echo $total_extra;
['extra'] time format is example "10:30"
I getting only hours in sum without min example "20", but i need full sum format like in "hours:mins"
Convert everything to minutes (using explode() is what you need here), do the math, then convert it back to "hour:min".
$a = '10:30';
$b = '4:20';
$aExploded = explode(':', $a);
$bExploded = explode(':', $b);
$aMinutes = $aExploded[0]*60 + $aExploded[1];
$bMinutes = $bExploded[0]*60 + $bExploded[1];
$sum = $aMinutes + $bMinutes;
$sumString = floor($sum / 60).':'.($sum % 60);
echo $sumString;

PHP detect and remove unnecessary cent of price [duplicate]

This question already has answers here:
Closed 10 years ago.
For invoicing I want to determine if my total amount has an unnecessary cent. e.g. $5.01 or $5.51. If it detects the cent then I run an if statement to remove the cent: minus 0.01
eg.
Change 30.51 to 0.01 and give a warning message
and also
30.51 to 0.51
and also
30.51 to 1
Both come from a POST, so they are both PHP strings.
but no worries - i got it to work now thanks to dmayo
$pieces = explode(".", $TotalAmt);
echo "<br>p1:".$pieces[1]; // piece2
$p1 = $pieces[1];
$spl1 = str_split($p1);
$TAmttmp = 0;
//echo "<br>sp11:".$spl1; // error convert array to string
$TAmttmp = $spl1[0];
echo "<br>TAmttmp: with useless cent".$TAmttmp;
echo "<br>IT:".$IT;
if ($TAmttmp == 0.01) //so if there is 1 cent subtract the useless cent.
$TAmt = $TAmt - 0.01;
echo "<br>TAmt: with useless cent".$TAmt;
echo "<br>TAmt: without useless cent".$TAmt;
#Gumbo is right, we need to know the logic behind your conversions to provide a precise answer.
You could do an explode:
$var = explode('.',$_POST['val']);
$digits = $var[1]; // this will give you the digits after the decimal point
Now you can do what you need based on your logic.
You could also you use a substr() where you find the decimal point (is it always three places from the right?) and then grab the substring.
Not sure which would be more efficient.
I don't know exactly what you want, but perhaps that helps:
$nr = "30.51";
echo round($nr - floor($nr), 2); // 0.51
echo round(($nr * 10 - floor($nr * 10)) / 10, 2); // 0.01
echo round(($nr * 10 - floor($nr * 10)) * 10); // 1

Categories