JavaScript中Math.round()函数使用方法

1,095 阅读1分钟

Javascript Math Round Example Tutorial

数学中的四舍五入涉及到用一个数字的近似值来代替一个数字,这个近似值会使上述数字在特定的四舍五入定义的基础上变得更短、更直接或更明确。

JavaScript的Math.round

JavaScript的**Math.round()**是一个内置函数,用于返回一个四舍五入到最接近的整数的数字的值。 Math.round() 方法将数字四舍五入到最接近的整数。

如果一个参数的小数部分超过0.5,该参数将被转为一个绝对值次高的整数。 如果小于0.5,那么参数将被四舍五入为较低值的整数。最后,如果小数部分正好是0.5,则参数被四舍五入为下一个+∞方向的整数。

语法

Math.round(x)

参数

x 是一个数字时,给定数字的值被四舍五入到最接近的整数。

让我们看看下面的例子。

// app.js

console.log(Math.round(21.19));
console.log(Math.round(19.21));
console.log(Math.round(46.21));
console.log(Math.round(21.52));

输出

Javascript Math Round Example | Math.round() Tutorial

**Math.round()**函数返回一个被四舍五入到最接近的整数的数字值。

如果我们想把一个数字四舍五入到最接近的整数,应该实现**Math.round()**函数。

当作为参数传递时,**Math.round()**函数本身会舍弃一个负数。请看下面的例子。

// app.js

console.log(Math.round(-21.52));

输出

Math.round() Tutorial

脚本Math.round到小数点后2位

要在JavaScript四舍五入 小数点2位,请使用Math.round() 函数。**Math.round()**函数返回一个四舍五入到最接近的整数的数字值。

// app.js

let num = 21.39999

let rnd = Math.round(num * 100) / 100
console.log(rnd)

输出

21.4

JavaScript Math.round四舍五入到小数点后1位

要在JavaScript四舍五入到 小数点1 ,请使用**math.round()**函数。

// app.js

let num = 21.111111

let rnd = Math.round(num * 10) / 10
console.log(rnd)

输出

21.1

本教程就到此为止。