chriswiec
chriswiec

Reputation: 1211

Division of decimal part of number only

Is there anyway to divide the decimal of a number instead of the whole number. Like if I have a number that is 3.99 I would want to divide only the decimal by 1.66667. I want to do this because 3.99 is supposed to equal 3 minutes 59 seconds, so I would rather have it read 3.59 instead of 3.99.

This is the code I have to return the time now, btw it is returning a time from a program that is telling you how much time till something is due. But is used as a full two decimal number format.

function GetDiff(dt) { 
    sMins = " Min";
    sHours = " Hours";
    sDays = " Days";
    sSecs = " Secs";

    if (Math.abs(DateDiff("s", now, dt)) < 86400) {
        if (Math.abs(DateDiff("s", now, dt)) <= 3600) {
            return ((Math.floor(Math.abs(
                     DateDiff("s", now, dt) / 60) * 100) / 100
                     ).toFixed(2) + sMins);
        }
        else
        {
            return ((Math.floor(Math.abs(
                     DateDiff("s", now, dt) / 3600) * 100) / 100
                     ).toFixed(2) + sHours);
        }
    }
    else
    {
        return ((Math.floor(Math.abs(
                 DateDiff("s", now, dt) / 86400) * 100) / 100
                 ).toFixed(2) + sDays);
    }
}

Upvotes: 0

Views: 315

Answers (4)

Isaac Suttell
Isaac Suttell

Reputation: 469

How about:

var number = 3.99,
    percentOfSeconds = number - Math.floor(number), // result: .99;
    seconds = Math.floor(percentOfSeconds * 60);    // result 59

This doesn't take into account for leading zeros and such through.

Upvotes: 1

JLRishe
JLRishe

Reputation: 101768

you can use number % 1 to get the decimal portion of a number:

var number = 3.99;                
alert((number % 1) / 1.666667);         // result: 0.59399.....
alert(Math.floor((number % 1) * 60));   // result: 59

Upvotes: 1

Mike
Mike

Reputation: 1837

Assuming we are talking about 3.99 minutes I would start by converting them to seconds (the unit we really care about). With the total number of seconds you can then divide by 60 and chop off any remainder using Math.floor to get the number of minutes. You can then floor the result of the total number of seconds modulus 60 to get the "remaining seconds".

var decimalMinutes = 3.99;

var totalSeconds = decimalMinutes * 60;
var totalMinutes = Math.floor(totalSeconds / 60);
var remainingSeconds = Math.floor(totalSeconds % 60);

// Outputs 3:59
console.log(totalMinutes + ":" + remainingSeconds);

// Float of 3.59
console.log(parseFloat(totalMinutes + "." + remainingSeconds));

// Float of 3.59 without type juggling
console.log(totalMinutes + (remainingSeconds / 100));

Fiddle

Upvotes: 1

Horst
Horst

Reputation: 1739

You get the minutes - 3, and 0.99 minutes Just 0.99*60 to get the seconds and append it to the minutes return "3"+"."+"59" + sMins

But it is not recommended to display "." for this case....

Upvotes: 1

Related Questions