在 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() 方法将数字四舍五入到小数点后三位。
该方法采用的唯一参数是应出现在小数点后的位数。
在第二个示例中,我们有一个字符串,它是一个有效数字。
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
数字 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 等数字。
代码四舍五入到最接近的数字,导致四舍五入错误。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。