js 計算精度問題

一 js 計算精讀出現的問題枚舉

二 js 浮點計算 精度出現精讀問題的原因

二 js 浮點運算解決方案 (保留多少位數小數,末尾實現四捨五入)

方法一: 自定義函數
    function toFixed(n, d) {
      if (n > Number.MAX_SAFE_INTEGER || n < Number.MIN_SAFE_INTEGER) {
        throw new Error('超過js安全計算值範圍,此函數暫不支持!');
      }
      const radix = 10 ** d;
      let num = math.floor(n * radix);
      const a = String(n).split('.');
      if (a[1] && a[1].length >= d) {
        if (Number(a[1][d]) >= 5) {
          num += 1;
        }
      }
      return num / radix;
    }
方法二 利用mathjs 庫
import { create, all, round } from 'mathjs';

const config = {
  number: 'BigNumber',
  precision: 64,
};

const mathJs = create(all, config);
// number 和 bignumber類型
// mathJs.evaluate('0.1 + 0.2');  // 0.3
// 默認保留兩位小數,實現四捨五入

export const math = (expression, precision = 2) => {
  return round(mathJs.number(mathJs.evaluate(expression)), precision);
};

math('0.1 + 0.2'); // 0.3
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章