首页 > 解决方案 > 负数转换为负数

问题描述

<?php           
    function convertToHoursMins($total, $format = '%02d:%02d') {
        $hours = intval($total / 60);
        $minutes = ($total % 60);
        return sprintf($format, $hours, $minutes);
    } 
    echo convertToHoursMins($total, $format = '%02d:%02d');
?>

当 $total 为正时,此解决方案非常有效(与许多其他解决方案一样)。另一方面,当 $total 为负数时,$hours 和 $minutes 都会像 -hours:-minutes 一样为负数。我尝试过的每个解决方案都会回显相同的输出,我感到很沮丧。我真的很木感谢一些帮助!

标签: phpformat

解决方案


一种解决方案是使用的绝对值$total-在需要时添加:

function convertToHoursMins($total, $format = '%02d:%02d') 
{
    $absTotal = abs($total);
    $hours = intval($absTotal / 60);
    $minutes = ($absTotal % 60);
    return sprintf((0 <= $total ? '' : '-') . $format, $hours, $minutes);
} 

推荐阅读