javascript - 如何舍入到最接近的整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7172835/
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-10-25 23:11:40  来源:igfitidea点击:

javascript - how to round to nearest integer

javascriptmath

提问by Mazatec

Possible Duplicate:
How can I round of to whole numbers in JavaScript?

可能的重复:
如何在 JavaScript 中四舍五入到整数?

In javascript is there a function which allows me to round to the nearest integer? Either up or down.

在javascript中是否有一个函数可以让我四舍五入到最接近的整数?无论是向上还是向下。

So:

所以:

2.1 = 2
2.9 = 3
4.5 = 5
1.1 = 1

2.1 = 2
2.9 = 3
4.5 = 5
1.1 = 1

回答by dacwe

Use Math.round(number):

使用Math.round(number)

var i = Math.round(2.1);

回答by NimChimpsky

Math.round(x)and Math.floor(x)

Math.round(x)Math.floor(x)

both documented here

都记录在这里

回答by Rolando Cruz

use Math.round()

使用 Math.round()

EDIT:

编辑:

Mine was wrong the one above me is correct

我的错了我上面的那个是正确的