日期:2014-05-16  浏览次数:20342 次

js浮点数精确计算函数(加,减,乘,除)

?come from http://www.cnblogs.com/konooo/archive/2010/01/23/1654617.html

?

  1. //浮点数加法运算??
  2. ?function?FloatAdd(arg1,arg2){??
  3. ???var?r1,r2,m;??
  4. ???try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}??
  5. ???try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}??
  6. ???m=Math.pow(10,Math.max(r1,r2))??
  7. ???return?(arg1*m+arg2*m)/m??
  8. ??}??
  9. ??
  10. ?//浮点数减法运算??
  11. ?function?FloatSub(arg1,arg2){??
  12. ?var?r1,r2,m,n;??
  13. ?try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}??
  14. ?try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}??
  15. ?m=Math.pow(10,Math.max(r1,r2));??
  16. ?//动态控制精度长度??
  17. ?n=(r1>=r2)?r1:r2;??
  18. ?return?((arg1*m-arg2*m)/m).toFixed(n);??
  19. ?}??
  20. ???
  21. ?//浮点数乘法运算??
  22. ?function?FloatMul(arg1,arg2)???
  23. ?{???
  24. ??var?m=0,s1=arg1.toString(),s2=arg2.toString();???
  25. ??try{m+=s1.split(".")[1].length}catch(e){}???
  26. ??try{m+=s2.split(".")[1].length}catch(e){}???
  27. ??return?Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)???
  28. ??}???
  29. ??
  30. ??
  31. //浮点数除法运算??
  32. function?FloatDiv(arg1,arg2){???
  33. var?t1=0,t2=0,r1,r2;???
  34. try{t1=arg1.toString().split(".")[1].length}catch(e){}???
  35. try{t2=arg2.toString().split(".")[1].length}catch(e){}???
  36. with(Math){???
  37. r1=Number(arg1.toString().replace(".",""))???
  38. r2=Number(arg2.toString().replace(".",""))???
  39. return?(r1/r2)*pow(10,t2-t1);???
  40. }???
  41. }??