在 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 等数字。
代码四舍五入到最接近的数字,导致四舍五入错误。
相关文章
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
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。