JavaScript Math round()

Math.round() 函数返回最接近的整数。也就是说,3.87 圆整为 4,而 3.45 圆整为 3

示例

let number = 3.87;

// round the number to nearest integer let roundedNumber = Math.round(number);
console.log(roundedNumber); // Output: 4

Math.round() 语法

Math.round() 函数的语法是

Math.round(x)

round() 作为静态方法,通过 Math 类名调用。


Math.round() 参数

Math.round() 函数接收

  • x - 一个数字

Math.round() 的返回值

Math.round() 返回最接近的整数值,具体如下:

  • 如果 **小数部分 > 0.5**,则 x 将圆整到绝对值更大的整数。
  • 如果 **小数部分 < 0.5**,则 x 将圆整到绝对值更小的整数。
  • 如果 **小数部分 = 0.5**,则 x 将圆整到绝对值方向上的下一个整数(即趋向 +∞)。

示例:使用 Math.round()

// using Math.round()
var num = Math.round(1.8645);
console.log(num); // 2 var num = Math.round(10.49); console.log(num); // 10
var num = Math.round(4.5);
console.log(num); // 5 var num = Math.round(-4.5); console.log(num); // -4 // Returns 0 for null
var num = Math.round(null);
console.log(num); // 0 // Returns NaN for non-numeric types
var num = Math.round("JavaScript");
console.log(num); // NaN

输出

2
10
5
-4
0
NaN

注意: Math.round() 对于 null 返回 0 而不是 NaN


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战