在 JavaScript 中将数字四舍五入到小数点后两位
本教程介绍了如何在 JavaScript 中将数字四舍五入到小数点后两位。
我们对数字应用 .toFixed()
方法,并将小数点后的位数作为参数。
var numb = 12312214.124124124;
numb = numb.toFixed(2);
在某些情况下,此方法无法获得准确的结果,并且有比该方法更好的方法。如果数字四舍五入为 1.2
,则它将显示为 1.20
。如果给出的数字是 2.005
,它将返回 2.000
,而不是 2.01
。
我们将数字加上一个非常小的数字 Number.EPSILON
,以确保数字的精确舍入。然后,我们在舍入前将数字乘以 100
,以仅提取小数点后两位。最后,我们将数字除以 100,以获得最多 2 个小数位。
var numb= 212421434.533423131231;
var rounded = Math.round((numb + Number.EPSILON) * 100) / 100;
console.log(rounded);
输出:
212421434.53
尽管此方法比 .toFixed()
有所改进,但它仍然不是最佳解决方案,也无法正确舍入 1.005
。
在此方法中,我们使用 .toPrecision()
方法来消除在单次舍入中的中间计算过程中引入的浮点舍入误差。
function round(num) {
var m = Number((Math.abs(num) * 100).toPrecision(15));
return Math.round(m) / 100 * Math.sign(num);
}
console.log(round(1.005));
输出:
1.01
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
console.log(roundToTwo(2.005));
这个自定义函数可以处理所有的极端情况,该函数可以很好地处理小数点后的小数(如 1.005
)。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。