如何在JavaScript中实现任意精度(如28位小数)的除法运算
解决高精度小数的精确运算问题
问题根源
你遇到的核心问题是:
- decimal.js 默认仅保留20位有效数字,目标数值
1.1998679030467029262556391239有29位有效数字,超出默认精度导致截断/四舍五入 - exact-math 默认限制小数位数为17位,无法完整保留28位小数的精度
针对 decimal.js 的解决方案
修改decimal.js的全局精度配置,将有效数字位数设为足够大(比如30),确保覆盖目标数值长度:
import { Decimal } from 'decimal.js'; // 全局配置:设置有效数字精度为30,足够容纳28位小数+1位整数 Decimal.set({ precision: 30 }); describe('decimals.js', () => { testCases.forEach((testCase) => { test(testCase, () => { const result = new Decimal(testCase).div(1).toFixed(28); expect(result).toBe(testCase); }); }); });
注意:precision指有效数字总数,不是小数位数,设置为30可完全覆盖你的29位有效数字需求。
针对 exact-math 的解决方案
调用exactMath.div时指定decimalPlaces为28,并关闭自动四舍五入:
import exactMath from 'exact-math'; describe('exact-math', () => { testCases.forEach((testCase) => { test(testCase, () => { const result = exactMath.div(testCase, 1, { returnString: true, decimalPlaces: 28, rounding: 'truncate' }); expect(result).toBe(testCase); }); }); });
如果exact-math的小数位数限制仍无法满足需求,建议换用更专注于高精度精确运算的库。
更稳妥的替代方案:使用 big.js
big.js 以精准处理十进制运算为设计目标,默认不限制精度(仅受内存约束),无需额外配置即可通过所有测试:
import Big from 'big.js'; describe('big.js', () => { testCases.forEach((testCase) => { test(testCase, () => { const result = new Big(testCase).div(1).toFixed(28); expect(result).toBe(testCase); }); }); });
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

