准确的JS浮点四则运算方法

2020-10-06  本文已影响0人  microkof

原则就一条:永远只让整数进行运算。

/**
 * @param a
 * @param b
 */

const add = (a, b) => {
  let c = 0,
    d = 0,
    e;
  try {
    c = a.toString().split(".")[1].length;
  } catch (z) {}
  try {
    d = b.toString().split(".")[1].length;
  } catch (z) {}
  e = Math.pow(10, Math.max(c, d));
  return (mul(a, e) + mul(b, e)) / e;
}

const sub = (a, b) => {
  let c = 0,
    d = 0,
    e;
  try {
    c = a.toString().split(".")[1].length;
  } catch (z) {}
  try {
    d = b.toString().split(".")[1].length;
  } catch (z) {}
  e = Math.pow(10, Math.max(c, d));
  return (mul(a, e) - mul(b, e)) / e;
}

const mul = (a, b) => {
  let c = 0,
    d = a.toString(),
    e = b.toString();
  try {
    c += d.split(".")[1].length;
  } catch (z) {}
  try {
    c += e.split(".")[1].length;
  } catch (z) {}
  return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}

const div = (a, b) => {
  let c, d, e = 0, f = 0;
  try {
    e = a.toString().split(".")[1].length;
  } catch (z) {}
  try {
    f = b.toString().split(".")[1].length;
  } catch (z) {}
  c = Number(a.toString().replace(".", ""));
  d = Number(b.toString().replace(".", ""));
  return mul(c / d, Math.pow(10, f - e));
}

export default {add, sub, mul, div};
上一篇下一篇

猜你喜欢

热点阅读