Reputation: 63
I need to subtract numbers in my table and i'm using php to get the result e.g 17.45 - 7.15. The result im getting is a whole number. How can i get the difference of the two numbers with its decimal point in two decimal places?
Here is the code i've been trying.
<td><?php echo substr($list->m_time, 0,5) ?></td>
<td><?php echo substr($list->mx_time, 0,5)?></td>
<td><?php echo substr($list->mx_time, 0,5) - substr($list->m_time, 0,5)?></td>
and here is my output:
Thanks and have a nice day!
Upvotes: 3
Views: 5306
Reputation: 565
$result = floatval($list->mx_time) - floatval($list->m_time);
echo round(floatval($result),2);
I am giving somethng in other way around..
10:32 means 10 hours 32 mins
SO first we need to explode it like this
$start_time = explode(":",$m_time); //where m_time = 10:32
$start_time_hr = $start_time[0];
$start_time_min = $start_time[1];
$start_tot_min = intval($start_time_hr*60) + $start_time_min;
similarly
$end_time = explode(":",$mx_time); //where mx_time = 11:45
$end_time_hr = $end_time[0];
$end_time_min = $end_time[1];
$end_tot_min = intval($end_time_hr*60) + $end_time_min; //converting hour to min + min
now $total_min_diff = intval($end_tot_min - $start_tot_min);
then total hr_diff = intval($total_min_diff/60);
total min_diff = intval($total_min_diff%60);
There for time difference is $hr_diff Hours and $min_diff Minutes
i.e.
<?php echo "The total Difference Is : ".$hr_diff." Hours & ".$min_diff." Minutes.";?>
Upvotes: 6
Reputation: 821
try this:
$datetime1 = new DateTime('17:13');
$datetime2 = new DateTime('10:32');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%H:%i');
echo $elapsed;
Upvotes: 2
Reputation: 1439
Try using below code, that should for you
echo number_format((float)((float)$list->mx_time - (float)$list->m_time), 2, '.', '');
Or
echo number_format((float)($list->mx_time - $list->m_time), 2, '.', '');
Upvotes: 0
Reputation: 2584
Just use it like this
$result = $list->mx_time - $list->m_time;
echo round($result,2);
values are float, so don't use string functions
Upvotes: 0