浮点型加减乘除失去精度问题解决方案

121 阅读1分钟
//获取小数位长度
function getDecimalLength(num:any){ 
  let length=0;
  try{
      length =String(num).split('.')[1].length
  }catch(e){
      //TODO handle the exception
  }
  return length;
}
//获取放大倍数
function getBeishu(num1:any,num2:any){  
  let num1DecimalLength=getDecimalLength(num1);
  let num2DecimalLength=getDecimalLength(num2);
  let longer=Math.max(num1DecimalLength,num2DecimalLength);
  return Math.pow(10,longer);
}


//加减乘除算法
function add(num1:any,num2:any){
  let beishu=getBeishu(num1,num2);
  return (num1*beishu+num2*beishu)/beishu;
}

function sub(num1:any,num2:any){
  let beishu=getBeishu(num1,num2);
  return (num1*beishu-num2*beishu)/beishu;
}

export function mul(num1:any,num2:any){
  let num1DecLen=getDecimalLength(num1);
  let num2DecLen=getDecimalLength(num2);
  let num1toStr=String(num1);
  let num2toStr=String(num2);
  return Number(num1toStr.replace('.',''))*Number(num2toStr.replace('.',''))/Math.pow(10,num1DecLen+num2DecLen)
}


function dev(num1:any,num2:any){
  let num1DecLen=getDecimalLength(num1);
  let num2DecLen=getDecimalLength(num2);
  let num1toStr=String(num1);
  let num2toStr=String(num2);
  return Number(num1toStr.replace('.',''))/Number(num2toStr.replace('.',''))/Math.pow(10,num1DecLen-num2DecLen)
}