自学内容网 自学内容网

JavaScript数字精度丢失问题解决方案

JavaScript数字精度丢失问题

JavaScript使用64位浮点数表示数字(基于IEEE 754标准),这导致某些十进制数字在计算过程中出现精度丢失。常见的场景包括小数运算,如 0.1 + 0.2 的结果并非精确的 0.3,而是 0.30000000000000004

解决方法

  1. 使用toFixed()toPrecision():对计算结果四舍五入,但这仅适用于显示层面。

    let result = (0.1 + 0.2).toFixed(2); // "0.30"
    
  2. 将数字转换为整数再计算:将小数放大为整数,运算后再缩小。

    let result = (0.1 * 10 + 0.2 * 10) / 10; // 0.3
    
  3. 使用Big.js、Decimal.js等库:处理精度问题,专门解决浮点数运算的库。

    const Decimal = require('decimal.js');
    let result = new Decimal(0.1).plus(0.2).toNumber(); // 0.3
    

案例

console.log(0.1 + 0.2); // 输出:0.30000000000000004
console.log((0.1 * 10 + 0.2 * 10) / 10); // 输出:0.3

使用库:

const Decimal = require('decimal.js');
let result = new Decimal(0.1).plus(0.2).toNumber(); // 输出:0.3

原文地址:https://blog.csdn.net/misstianyun/article/details/142729837

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!