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

JS处理浮点数计算问题
问一下,JS处理浮点数有没有好点的函数啊.
浮点数相加,相减,相乘

------解决方案--------------------
function demicalFloat(numberA,numberB,type)
{
var h=(type== "* ")? "+ ": "- ";
var c=[get(numberA),get(numberB)];
var A=c[0][1]; //numberA 的數字
var B=c[1][1]; //numberB 的數字
var pointA=c[0][0]; //numberA 的小數位數
var pointB=c[1][0]; //numberB 的小數位數

if (type== "* " || type== "/ ")
{
var k1=eval( "numberA "+type+ "numberB ");
var k2=eval( "(A "+type+ "B) ");
if (get(k1)[1]==k2) return k1;
else return (pointA+pointB==0? k1:eval(k2+ "/Math.pow(10,pointA "+h+ "pointB) "));
}
else if (type== "+ " || type== "- ")
{
var pointL=pointA;
if (pointA <pointB) pointL=pointB;
numberA=demicalFloat(numberA,Math.pow(10,pointL), "* ");
numberB=demicalFloat(numberB,Math.pow(10,pointL), "* ");
return eval( "numberA "+type+ "numberB ")/Math.pow(10,pointL);
}
else return "[ Can 't calculate! ] "
}

function get(number)
{
number= " "+number;
if (number.indexOf( ". ")==-1) return [0,parseInt(number)];
//小數位數
var po=number.split( ". ")[1].length;
//轉成整數 4.1 --> 41 , 4.33 --> 433
var st=number.split( ". ").join( " ");
//將前置 0 拿掉
for (var i=0;i <st.length;i++) if (st.charAt(0)== "0 ") st=st.substr(1,st.length);
//傳回一個陣列,陣列 0 存小數位數, 陣列 1 存數字
return [po,parseInt(st)];
}

------解决方案--------------------
javascript里面浮点数精度损失确实是个问题
----------------------------------
http://community.csdn.net/Expert/TopicView.asp?id=5614601
------解决方案--------------------
<script defer>
Number.prototype.rate=function(){
var oStr=this.toString();
if(oStr.indexOf( ". ")==-1)
return 1;
else
return Math.pow(10,parseInt(oStr.length-oStr.indexOf( ". ")-1));
}

function tran(){
args=tran.arguments;
var temp=1;
for(i=0;i <args.length;i++)
temp*=args[ i ]*args[ i ].rate();
for(i=0;i <args.length;i++)
temp/=args[ i ].rate();
return temp
}

alert(tran(11,3.56));

</script>
------解决方案--------------------
/*
* 四则运算精度修正函数
* m 数值1(number)
* n 数值2(number)
* op 操作符(string)
*/
function fixMath(m, n, op) {
var a = (m+ " ");
var b = (n+ " ");
var x = 1;
var y = 1;
var c = 1;
if(a.indexOf( ". ")> 0) {
x = Math.pow(10, a.length - a.indexOf( ". ") - 1);
}
if(b.indexOf( ". ")> 0) {
y = Math.pow(10, b.length - b.indexOf( ". ") - 1);
}
switch(op)
{
case '+ ':
case '- ':
c = Math.max(x,y);
m = Math.round(m*c);
n = Math.round(n*c);
break;
case '* ':
c = x*y
m = Math.round(m*x);
n = Math.round(n*y);
break;
case '/ ':
c = Math.max(x,y);
m = Math.round(m*c);
n = Math.round(n*c);
c = 1;
break;
}
return eval( "( "+m+op+n+ ")/ "