How to subtract numbers with decimal point in php

I need to subtract numbers in my table and I am using php to get the result like 17.45 - 7.15. The result im im is an integer. How can I get the difference between two numbers with a decimal point in two decimal places?

Here is the code I tried.

<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:

enter image description here

Thanks and have a nice day!

+3


source to share


4 answers


$result = floatval($list->mx_time) - floatval($list->m_time);
echo round(floatval($result),2);

      

I give something in a different way.

10:32 means 10 hours 32 minutes

SO first need to blow it up 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 the total hr_diff = intval($total_min_diff/60);

total min_diff = intval($total_min_diff%60);

There the difference in time is $ hr_diff Hours and $ min_diff Minutes

i.e.

<?php echo "The total Difference Is : ".$hr_diff." Hours & ".$min_diff." Minutes.";?>

      

+5


source


try this:



$datetime1 = new DateTime('17:13');
$datetime2 = new DateTime('10:32');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%H:%i');
echo $elapsed;

      

+2


source


Just use it like this

$result = $list->mx_time - $list->m_time;
echo round($result,2);

      

the values ​​are floats, so don't use string functions

0


source


Try using below code which 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, '.', '');

      

0


source







All Articles