JavaScript数学的四舍五入

4

可能是重复问题:
JavaScript的Math函数有问题吗?

好的,我有这个脚本:

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

它完美地工作着,除了有时会给我一个像 4.000016666666666 这样的答案。我该如何四舍五入呢?如果必须重写脚本也可以。谢谢!


2
你有没有尝试使用搜索功能?有很多重复的内容。 - Alexandre C.
可能是JavaScript的Math有问题吗?的重复问题-其他很多很多。 - Andy E
嗯,不妨试试http://www.google.com/search?q=javascript+round? - Jakub Hampl
我已经搜索过了。我得到了一些奇怪的代码片段,我必须想办法将其放入我的脚本中。 - 0x60
嗯... 我最接近的重复是 <a href="https://dev59.com/G3RB5IYBdhLWcg3wj36c">this</a>。 - 0x60
4个回答

14

您可以使用 Math.floor() 函数进行“向下取整”操作。

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

或者 Math.ceil(),它会 '向上取整'

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

或者使用Math.round()函数,可以将数字四舍五入到最接近的整数:

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

2

Math.Round不会起作用;Round不是构造函数,因此不以大写字母R开头。 - Martijn

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

使用 parseInt()


0
如果你正在寻找简单的数学四舍五入,那么这里就是 Math.round(40.45);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接