代码如下:
var numarr = [190.60,136.70];
var total = 0;
for(var i=0; i<numarr.length; i++)
{
       var x = parseFloat(numarr[i]);
       alert(x);
       total += x;
       alert(total)
}执行完的结果竟然产生了很多的小数点。。这是怎么回事呢?

解决方案 »

  1.   

    用toFixed(2)方法可以保留2位小数!至于为什么会这样 我也不清楚
      

  2.   

    js 是弱类型语言,不区分float 和 double解决js的float型变量加减精度问题<script type="text/javascript">
    Number.prototype.getB = function(){
    var arr = this.toString().split('.');
    return arr[1]? arr[1].length : 0;
    }
    Number.prototype.getP = function(to){
    return Math.pow(10, Math.max(this.getB(), to.getB()));
    }
    Number.prototype.add = function(to){
    var p = this.getP(to);
    return (this * p + to * p) / p;
    }
    Number.prototype.sub = function(to){
    var p = this.getP(to);
    return (this * p - to * p) / p;
    }
    var a = 123.321
    var b = 111.1
    var c = 12.221
    alert([a + b, a.add(b)]);
    alert([a - b, a.sub(b)]);
    alert([a - b == c, a.sub(b) == c]);
    </script>
      

  3.   

    楼上已经正确了。
    total.toFixed(2)