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;
Related
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);
$a = 01:04:06:02:55:28
$b = 03:04:06:02:54:34
//format("%Y:%M:%D:%H:%I:%S")
I would like to find average of these two.
In this case $a is time taken to finish task 1 and $b is time taken to finish task 2, Now I would like to know average time taken by the person to complete two tasks.
You can calculate the mean of the two timestamp. live demo
<?php
$a = '01:04:06:02:55:28';
$b = '03:04:06:02:54:34';
$aTimestamp = DateTime::createFromFormat('m:d:y:h:i:s', $a, new DateTimeZone('Europe/Warsaw'))->getTimestamp();
$bTimestamp = DateTime::createFromFormat('m:d:y:h:i:s', $b, new DateTimeZone('Europe/Warsaw'))->getTimestamp();
echo date("m:d:y:h:i:s", ($aTimestamp + $bTimestamp)/2);
You should use timedelta objects if your format corresponds to a duration and not exact dates (see live demo or code below, assuming 1 year=365 days and 1 month=30 days). Notice that timedelta objects accept just days (rather than months or years, avoiding ambiguity). Timedelta objects allow arithmetic operations (see https://docs.python.org/2.4/lib/datetime-timedelta.html)
Datetime objects assume a calendar, which means that they would use the actual duration of months and years between the two points (with months ranging 28-31 and maybe leap years instead of "standard" durations).
from datetime import timedelta
a = "01:04:06:02:55:28"
b = "03:04:06:02:54:34"
(y,mo,d,h,mi,s) = a.split(":");
tda = timedelta(days=int(y)*365+int(mo)*30+int(d), hours=int(h), minutes=int(mi), seconds=int(s));
(y,mo,d,h,mi,s) = b.split(":");
tdb = timedelta(days=int(y)*365+int(mo)*30+int(d), hours=int(h), minutes=int(mi), seconds=int(s));
print("a: " + str(tda))
print("b: " + str(tdb))
print("average: " + str((tda+tdb)/2))
# now we only need to format the output as needed
avgtd = (tda+tdb)/2
avgy = avgtd.days/365
avgm = (avgtd.days - avgy*365) / 30
avgd = (avgtd.days - avgy*365 - avgm*30)
avghou = avgtd.seconds / 3600
avgmin = (avgtd.seconds - avghou*3600) / 60
avgsec = (avgtd.seconds - avghou*3600 - avgmin*60)
print("average: " + str(avgtd))
print ("{}:{}:{}:{}:{}:{}".format(avgy,avgm,avgd,avghou,avgmin, avgsec))
Alternatively, you could just calculate the average of each field. But I think it would be strange having 0.5 years, 0 months, 0 days instead of having 0 years, 6 months. The code would be easier, though, if this is a valid option:
a = "01:04:06:02:55:28"
b = "03:04:06:02:54:34"
(ay,amo,ad,ah,ami,asec) = a.split(":");
(by,bmo,bd,bh,bmi,bsec) = b.split(":");
print ("{}:{}:{}:{}:{}:{}".format((int(ay)+int(by))/2.0,(int(amo)+int(bmo))/2.0,(int(ad)+int(bd))/2.0,(int(ah)+int(bh))/2.0,(int(ami)+int(bmi))/2.0,(int(asec)+int(bsec))/2.0))
This question already has answers here:
How do I convert output of number_format back to numbers in PHP?
(12 answers)
Closed 1 year ago.
I used number_format in a number. I want to know how to convert number-formatted variable in php back to its original format
I first used number_format. And I want to echo back its original format removing the number format.
$number = 500000
echo number_format($number, 2);
$number = 500000;
$formattedNumber = number_format($number, 2);
$getBackOriginl = explode('.',$formattedNumber);
echo str_replace(',','',$getBackOriginl[0]);
This question already has answers here:
Print numeric values to two decimal places
(6 answers)
Closed 11 months ago.
hello i'm trying to find %. first i found the seconds
$tm=sum_the_time($d_duration);
$d_seconds='0';
list($hour,$minute,$second) = explode(':', $tm);
$d_seconds += $hour*3600;
$d_seconds += $minute*60;
$d_seconds += $second;
$total_second=$c_seconds+$p_seconds+$t_seconds+$b_seconds+$d_seconds;
$c_seconds=$c_seconds*100/$total_second;
$p_seconds=$p_seconds*100/$total_second;
$t_seconds=$t_seconds*100/$total_second;
$b_seconds=$b_seconds*100/$total_second;
$d_seconds=$d_seconds*100/$total_second;
echo $c_seconds;
the result is 10.754504504505, how would I print this code like 10.7
You can try using printf() function:
printf("%.1f", $c_seconds);
Or, number_format():
echo number_format( $c_seconds, 1 );
These two functions will round your number (will return 10.8 in your example), so, if you want to just truncate to the first decimal place (result to be equal to 10.7), you can use the following:
echo substr($c_seconds, 0, strpos($c_seconds, ".") + 2);
Actually, you can use the solutions from this question to better use number_format() and get your desired result.
echo sprintf('%0.1f', $c_seconds);
relevant docs here: http://php.net/sprintf
http://php.net/manual/en/function.number-format.php numberformat is propably what you are looking for.
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.