在 JavaScript 中,如果想要对一个数进行四舍五入,常用的有以下 2 种方式。
- 使用 Math.round() 方法。
- 使用 toFixed() 方法。
使用 Math.round() 实现四舍五入
在 JavaScript 中,我们可以使用 Math 对象的 round() 方法来将数字四舍五入到最接近的整数。如果数字的小数部分大于或等于 0.5,则向上舍入;否则,则向下舍入。
示例 1:使用 Math.round()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
console.log(Math.round(2.5));
console.log(Math.round(2.4));
</script>
</head>
<body>
</body>
</html>
运行结果如下。
3
2
使用 toFixed() 实现四舍五入
在 JavaScript 中,我们可以使用 Number 对象的 toFixed() 方法实现四舍五入。其中,toFxied() 会以 “字符串” 的形式来返回某个数字的 “四舍五入值”。
语法:
num.toFixed(n)
说明:
toFixed() 方法接收单个参数。
n(可选):用于指定小数点后有几位数字。如果 n 省略,则表示不带任何小数。
示例 2:toFixed() 不带参数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
const num = 3.1415;
const result = num.toFixed();
console.log(result);
console.log(typeof(result));
</script>
</head>
<body>
</body>
</html>
运行结果如下。
3
string
分析:
需要注意的是,toFixed() 方法返回的不再是数字,而是一个字符串。
示例 3:toFixed() 带参数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
const num = 3.1415;
const result1 = num.toFixed(1);
console.log(result1);
const result2 = num.toFixed(3);
console.log(result2);
</script>
</head>
<body>
</body>
</html>
运行结果如下。
3.1
3.142
分析:
当 toFixed() 方法带参数时,表示对指定位数的下一位进行四舍五入。
