如果需要,如何最多保留两位小数

发布时间 2023-10-18 20:47:52作者: 小满独家

内容来自 DOC https://q.houxu6.top/?s=如果需要,如何最多保留两位小数

可以使用JavaScript的toFixed()方法来实现。该方法可以将数字四舍五入到指定的小数位数,并返回一个字符串表示结果。如果需要,还可以在结果中保留指定的小数位数。

以下是一个实现该功能的示例代码:

[code]

javascript

function round(num, decimalPlaces) {

return parseFloat(num.toFixed(decimalPlaces));
}

let num1 = 10;
let num2 = 1.7777777;
let num3 = 9.1;

console.log(round(num1, 2)); // 输出 10.00
console.log(round(num2, 2)); // 输出 1.78
console.log(round(num3, 2)); // 输出 9.10

[/code]

在上面的代码中,round()函数接受两个参数:要四舍五入的数字和要保留的小数位数。它使用toFixed()方法将数字四舍五入到指定的小数位数,并将结果解析为浮点数类型。最后,它返回四舍五入后的结果。

然后,我们定义了三个数字变量num1num2num3,并将它们分别传递给round()函数来测试它的功能。最后,我们将结果打印到控制台上。


使用 Math.round()

Math.round(num * 100) / 100

或者更具体地确保像 1.005 这样的数字能够正确四舍五入,可以使用 Number.EPSILON

Math.round((num + Number.EPSILON) * 100) / 100