// 加法
function add(a, b) {
  const precision = Math.max(getPrecision(a), getPrecision(b));
  const multiplier = Math.pow(10, precision);
  return (multiply(a, multiplier) + multiply(b, multiplier)) / multiplier;
}

// 减法
function subtract(a, b) {
  const precision = Math.max(getPrecision(a), getPrecision(b));
  const multiplier = Math.pow(10, precision);
  return (multiply(a, multiplier) - multiply(b, multiplier)) / multiplier;
}

// 乘法
function multiply(a, b) {
  const precision = getPrecision(a) + getPrecision(b);
  const multiplier = Math.pow(10, precision);
  return Math.round(a * multiplier * b) / multiplier;
}

// 除法
function divide(a, b) {
  const precision = getPrecision(b) - getPrecision(a);
  const divisor = Math.pow(10, precision);
  return Math.round((a / b) * divisor) / divisor;
}

// 获取浮点数的精度
function getPrecision(num) {
  const str = num.toString();
  const decimalIndex = str.indexOf('.');
  return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
}

export {
  add,
  subtract,
  multiply,
  divide
}