JS 常用计算方法不丢精度

function safeAdd(nums:number[]) {
  return nums.reduce((total,current)=>{
    return total + current
  })
}
function safeMinus(nums:number[]) {
  return nums.reduce((total,current)=>{
    return total - current
  })
}
function safeMult(nums:number[]) {
  return nums.reduce((total,current)=>{
    return total * current
  })
}
function safeDivi(nums:number[]) {
  return nums.reduce((total,current)=>{
    return total / current
  })
}

export function safeCalc(calcMethod:'+' | '-' | '*' | '/', nums: number[], len: number = 2) {
  const pow = Math.pow(10, len);
  const methods = {
    '+': safeAdd,
    '-': safeMinus,
    '*': safeMult,
    '/': safeDivi
  }
  const newnums = nums.map(m=>m*pow)
  const result = methods[calcMethod](newnums) / pow
  return result;
}

你可能感兴趣的:(JS 常用计算方法不丢精度)