前端页面浮点数计算精度问题解决

前端页面浮点数计算存在的问题

// 0.1 + 0.2 = 0.30000000000000004 问题
console.log(0.1 + 0.2);

// 1.3333 * 150 = 199.99499999999998 问题
console.log(1.3333 * 150);

// 1.2 / 3 = 0.39999999999999997 问题
console.log(1.2 / 3);

使用decimal.js第三方库解决

  • 功能:支持任意精度的十进制运算,API 丰富(加减乘除、四舍五入、比较等)。
  • 安装:npm install decimal.js

使用示例:

import Decimal from 'decimal.js';

// 初始化 Decimal 实例(建议用字符串作为输入,避免浮点数本身的精度问题)
const a = new Decimal('0.1');       // 0.1
const b = new Decimal('0.2');       // 0.2
const c = new Decimal('3.1415');    // 3.1415
const d = new Decimal('2');         // 2


// 1. 加法(plus)
const sum = a.plus(b);
console.log(sum.toString());        // 输出: "0.3"(解决 0.1+0.2=0.30000000000000004 的问题)


// 2. 减法(minus)
const difference = c.minus(a);
console.log(difference.toString()); // 输出: "3.0415"(3.1415 - 0.1 = 3.0415)


// 3. 乘法(times / mul)
const product = c.times(d);         // 或 c.mul(d)
console.log(product.toString());    // 输出: "6.283"(3.1415 * 2 = 6.283)


// 4. 除法(dividedBy / div)
const quotient = b.dividedBy(d);    // 或 b.div(d)
console.log(quotient.toString());   // 输出: "0.1"(0.2 / 2 = 0.1)


// 进阶:链式操作(支持连续运算)
const chainResult = a.plus(b).times(c).dividedBy(d);
console.log(chainResult.toString()); // 计算 (0.1+0.2)*3.1415/2 → 输出: "0.471225"


// 保留小数位数(toFixed)
const fixedResult = chainResult.toFixed(2); // 保留 2 位小数(四舍五入)
console.log(fixedResult); // 输出: "0.47"

none
最后修改于:2025年11月19日 19:06

添加新评论