开发者

Converting pixels to minutes

I have an application where I convert pixels to minutes and hours. Basically using minutes as a unit of measure as such:

120 minutes = 240 px

I run that through this function:

convertToTime: function (min) {
    var hours = Math.floor( min / 60);          
    var minutes = Math.round(min % 60);
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (hours > 12) {
        hours = hours % 12;
    }
    return hours + ":" + minutes;
}

It is returning everything properly except for when minutes reaches 60. So for example it returns:

12:58 12:59 12:60

Which isn't what I want because that isn't a real time.

I think the issue is the 2 pixels to one minute ratio. But I am having trouble getting it nailed down.

An开发者_开发知识库y help is greatly appreciated thanks!


Do Math.floor(min) % 60 instead of Math.round(min % 60).

% is the modulus operator. x % 60 will always yield an integer value between 0 and 59 inclusive for positive integer x, which is what you want for your minutes display. Your problem is that min is not an integer - exactly half the time, since you are obtaining it by dividing an integer by 2. In particular, when your pixel count is 119, min is 59.5, and Math.round() will round that up to 60. Since % is unlikely to do what you want for floating point inputs in general, the correct solution is to make sure the value is an integer before you calculate its modulus, instead of trying to round it afterwards.


You are using Math.floor for the hours but Math.round for the minutes. You could fix your problem by using Math.floor for both of them!

convertToTime: function (min) {
    var hours = Math.floor( min / 60);          
    var minutes = Math.floor(min % 60);
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (hours > 12) {
        hours = hours % 12;
    }
    return hours + ":" + minutes;
}


You need too do

Math.round(Math.round(min) % 60)

or

Math.round(Math.floor(min) % 60)

or

Math.round(Math.ceil(min) % 60)

when you are using float may give you that error... example Math.round(59.5 % 60)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜