在 JavaScript 中将数字四舍五入到小数点后两位

本教程介绍了如何在 JavaScript 中将数字四舍五入到小数点后两位。

使用 .toFixed() 方法将 JavaScript 中的数字四舍五入到小数点后两位

我们对数字应用 .toFixed() 方法,并将小数点后的位数作为参数。

var numb = 12312214.124124124;
numb = numb.toFixed(2);

在某些情况下,此方法无法获得准确的结果,并且有比该方法更好的方法。如果数字四舍五入为 1.2,则它将显示为 1.20。如果给出的数字是 2.005,它将返回 2.000,而不是 2.01

在 JavaScript 中使用 Math.round() 函数将数字四舍五入到小数点后两位

我们将数字加上一个非常小的数字 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

在 JavaScript 中使用双舍入将数字四舍五入到小数点后两位

在此方法中,我们使用 .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

在 JavaScript 中使用自定义函数将数字四舍五入到小数点后两位

function roundToTwo(num) {
    return +(Math.round(num + "e+2")  + "e-2");
}
console.log(roundToTwo(2.005));

这个自定义函数可以处理所有的极端情况,该函数可以很好地处理小数点后的小数(如 1.005)。

在 JavaScript 中将数字四舍五入到小数点后 3 位

使用 toFixed() 方法将数字四舍五入到小数点后 3 位,例如 num.toFixed(3)。 toFixed 方法将数字格式化为指定的小数位数,并在必要时四舍五入该数字。

const num1 = 7.456677;
const result1 = num1.toFixed(3);
console.log(result1); // 👉️ 7.457
console.log(typeof result1); // 👉️ string

// 👇️ if the value is a string
// call parseFloat to convert it to a number first
const str1 = '7.456677';
const result2 = parseFloat(str1).toFixed(3);
console.log(result2); // 👉️ 5.457
console.log(typeof result2); // 👉️ string

// 👇️ Convert string back to a number
const num2 = 7.79999999;
const result3 = Number(num2.toFixed(3));
console.log(result3); // 👉️ 7.8
console.log(typeof result3); // 👉️ number

在第一个示例中,我们使用 Number.toFixed() 方法将数字四舍五入到小数点后三位。

该方法采用的唯一参数是应出现在小数点后的位数。

toFixed 方法返回数字的字符串表示形式。

在第二个示例中,我们有一个字符串,它是一个有效数字。

const str1 = '7.456677';
const result2 = parseFloat(str1).toFixed(3);
console.log(result2); // 👉️ 5.457
console.log(typeof result2); // 👉️ string

我们必须使用 parseFloat 函数将其转换为数字,因为 toFixed 方法只能在数字上调用。

在第三个示例中,我们使用 Number 对象将 toFixed 方法返回的字符串转换为数字。

const num2 = 7.79999999;
const result3 = Number(num2.toFixed(3));

console.log(result3); // 👉️ 7.8
console.log(typeof result3); // 👉️ number

但是,请注意删除了 2 个尾随零。 在 JavaScript 中将带有尾随零的字符串转换为数字时,不会保留任何尾随零。

数字 7.000 与 7 相同,因此当值转换为数字时尾随的零将被删除。

console.log(7.000 === 7); // 👉️ true

浮点数不能精确地以二进制表示所有小数,这会导致结果不一致。

console.log(0.1 + 0.2 === 0.3); // 👉️ false

0.1 和 0.2 的总和等于 0.30000000000000004 而不是 0.3。

这是因为二进制浮点格式无法准确表示 0.1 或 0.2 等数字。

代码四舍五入到最接近的数字,导致四舍五入错误。