JavaScript保留二十位小数:Math.round方法的局限性及Decimal.js解决方案
在 JavaScript 中,由于浮点数的精度问题,无法完全保留二十位小数。例如,使用 Math.round(222 * Math.pow(10, 20)) / Math.pow(10, 20) 这样的方法,只能得到 14 位小数,而且末尾还多了个 3。但你可以使用 Decimal.js 库来处理更高精度的数值计算。以下是使用 Decimal.js 实现保留二十位小数的示例代码:
const Decimal = require('decimal.js');
const result = new Decimal(222)
.times(new Decimal(10).pow(20))
.div(new Decimal(10).pow(20))
.toFixed(20);
console.log(result);
输出结果为:222.00000000000000000000,保留了二十位小数。注意,这里使用了 Decimal.js 库中的 Decimal 类来进行高精度计算。
原文地址: https://www.cveoy.top/t/topic/qC2H 著作权归作者所有。请勿转载和采集!