当前位置:首页 > 开发 > Web前端 > JavaScript > 正文

js float类型数据的加减乘除bug修复

发表于: 2013-01-06   作者:aahyhaa   来源:转载   浏览:
摘要: var FloatCalFun=new Object(); //获取参数精度,如果为整数则精度为0 FloatCalFun._getPrecision=function(arg){ if(arg.toString().indexOf(".")==-1){ return 0; }else{ return arg.toString().spl
var FloatCalFun=new Object();
//获取参数精度,如果为整数则精度为0
FloatCalFun._getPrecision=function(arg){
  if(arg.toString().indexOf(".")==-1){
     return 0;
  }else{
     return arg.toString().split(".")[1].length;
  }	
}
//获取小数的整数形式
FloatCalFun._getIntFromFloat=function(arg){
  if(arg.toString().indexOf(".")==-1){
     return arg;
  }else{
     return Number(arg.toString().replace(".",""));
  } 
}
//乘法
FloatCalFun.floatMulti=function(arg1,arg2){
  var precision1=this._getPrecision(arg1);
  var precision2=this._getPrecision(arg2);
  var tempPrecision=0;
  
  tempPrecision+=precision1;
  tempPrecision+=precision2;
  var int1=this._getIntFromFloat(arg1);
  var int2=this._getIntFromFloat(arg2);
  return (int1*int2)*Math.pow(10,-tempPrecision);
}
//加法
FloatCalFun.floatAdd=function(arg1,arg2){
  var precision1=this._getPrecision(arg1);
  var precision2=this._getPrecision(arg2);
  var temp=Math.pow(10,Math.max(precision1,precision2));
  return (this.floatMulti(arg1,temp)+this.floatMulti(arg2,temp))/temp;
}
//减法
//arg1 被减数
//arg2 减数
FloatCalFun.floatSubtract=function(arg1,arg2){
  var precision1=this._getPrecision(arg1);
  var precision2=this._getPrecision(arg2);
  var temp=Math.pow(10,Math.max(precision1,precision2));
  return (this.floatMulti(arg1,temp)-this.floatMulti(arg2,temp))/temp;
}
////除法
//arg1 被除数
//arg2 除数
FloatCalFun.floatDiv=function(arg1,arg2){
   var precision1=this._getPrecision(arg1);  
   var precision2=this._getPrecision(arg2); 
   var int1=this._getIntFromFloat(arg1);  
   var int2=this._getIntFromFloat(arg2);   
   var result=(int1/int2)*Math.pow(10,precision2-precision1);  
   return result;  
}
FloatCalFun.floatAdd(1.9,0.01);
alert(FloatCalFun.floatAdd(1.9,0.01));
alert(FloatCalFun.floatSubtract(1.9,0.01));
alert(FloatCalFun.floatDiv(1.9,0.01));
alert(FloatCalFun.floatMulti(1.9,0.01));
alert(1.9-0.01);

 

js float类型数据的加减乘除bug修复

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号