处理小数精度丢失问题

📅 2026/7/22 10:00:16 👁️ 阅读次数 📝 编程学习
处理小数精度丢失问题

import Fraction from 'fraction.js';

如果有e小数问题,先转成小数,再转成字符串,用Fraction处理,Fraction参数里尽量处理成字符串。否则会丢失精度。另外如果是无限小数,可以用分数表示。

// 将科学计数法转为普通小数字符串 例:把 7.85e-9 转成 "0.00000000785" 这个纯十进制字符串,再传给 Fraction。 function scientificToDecimal(num) { // 利用 toLocaleString 或手动转换,避免科学计数法 const str = num.toString(); if (!str.includes('e')) return str; const [base, exp] = str.split('e'); const exponent = parseInt(exp, 10); const digits = base.replace('.', '').replace('-', ''); const isNegative = num < 0; const sign = isNegative ? '-' : ''; // 计算小数点位置 const baseDotIndex = base.indexOf('.'); const actualDotPos = (baseDotIndex === -1 ? base.length : baseDotIndex) + exponent; let result; if (actualDotPos <= 0) { // 小数点在数字前面,需要补零 result = '0.' + '0'.repeat(-actualDotPos) + digits; } else if (actualDotPos >= digits.length) { // 小数点在数字后面,是整数 result = digits + '0'.repeat(actualDotPos - digits.length); } else { result = digits.slice(0, actualDotPos) + '.' + digits.slice(actualDotPos); } return sign + result; }

用法

let a=new Fraction(scientificToDecimal(String(num)))

let b=new Fraction(1, 3) //分数 1/3

a.sub(b)