解决 JavaScript 计算精度问题,可以使用以下方法:

115 阅读1分钟
  1. 使用 BigInt 类型处理大整数。
const bigInt1 = BigInt("9007199254740993");
const bigInt2 = BigInt("1234567890123456");
const bigIntResult = bigInt1 + bigInt2;
console.log(bigIntResult.toString()); // "10241767144864449"

  1. 使用 Number.toFixed() 方法处理小数计算精度问题。
const num1 = 0.1;
const num2 = 0.2;
const result = (num1 * 10 + num2 * 10) / 10;
console.log(result.toFixed(1)); // "0.3"

  1. 使用第三方库,如 decimal.js 或 bignumber.js

以 decimal.js 为例:

// 安装 decimal.js
// npm install decimal.js

const Decimal = require("decimal.js");

const num1 = new Decimal(0.1);
const num2 = new Decimal(0.2);
const result = num1.plus(num2);
console.log(result.toString()); // "0.3"