Javascript 数学四舍五入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5005275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:13:04  来源:igfitidea点击:

Javascript Math Rounding

javascriptjquerymath

提问by 0x60

Possible Duplicate:
Is JavaScript's Math broken?

可能的重复:
JavaScript 的数学有问题吗?

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!

它工作得很好。除了它有时会给我一个像4.000016666666666. 我怎样才能解决这个问题?如果我必须重写脚本,那没关系。谢谢!

回答by Mash

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

您可以使用 Math.floor() 函数来“四舍五入”

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

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

或 Math.ceil(),它“四舍五入”

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

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

或 Math.round(),向上或向下舍入,它更接近:

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

回答by powtac

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

use parseInt().

使用parseInt().

回答by Umair A.

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

如果您正在寻找简单的数学回合,那么这里是 Math.round(40.45);