开发者

Javascript Math Rounding [duplicate]

This question already has answers here: 开发者_C百科 Closed 11 years ago.

Possible Duplicate:

Is JavaScript's Math broken?

Okay, I have this script:

var x = new Date;
setInterval(function() {
    $("#s").text((new Date - x) / 60000 + "Minutes Wasted");
}, 30000);

It works perfectly fine. Except it sometimes gives me an answer like 4.000016666666666. How can I round that? If I have to rewrite the script, that is okay. Thanks!


You can use Math.floor() function to 'round down'

$("#s").text(Math.floor((new Date - x) / 60000 + "Minutes Wasted"));

or Math.ceil(), which 'round up'

$("#s").text(Math.ceil((new Date - x) / 60000 + "Minutes Wasted"));

or Math.round(), which round either up or down, where it's closer to:

$("#s").text(Math.round((new Date - x) / 60000 + "Minutes Wasted"));


Math.round?

See http://www.w3schools.com/jsref/jsref_obj_math.asp


setInterval(function() {
    $("#s").text(parseInt((new Date - x) / 60000) + "Minutes Wasted");
}, 30000);

use parseInt().


If you're looking for simple Math round then here it is Math.round(40.45);

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜