Lars Jensen
Lars Jensen

Reputation: 67

A negative number is converted too negative

<?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');
?>

This solution works perfect (like many other solutions) when $total is positive. When $total on the other hand is negative both $hours and $minutes gets negative like -hours:-minutes. Every solution I have tried echoes the same output, and I am getting frustrated. I really wood appreciate some help!

Upvotes: 1

Views: 112

Answers (2)

u_mulder
u_mulder

Reputation: 54841

One of solutions is to work with absolute value of $total and prepend - if required:

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

Upvotes: 1

TsV
TsV

Reputation: 639

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

Upvotes: 0

Related Questions