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

正确的JS四舍五入保留N为小数的算法怎么搞?
toFixed() 存在BUG
从网络上搜索了N种四舍五入的方法,经过测试都不太正确。
如:明明设置为保留两位小数,有时却出现了三位,而且计算结果,和人工计算结果有偏差。


------解决方案--------------------
以下应该可以满足你
JScript code

function roundTo(num, unit){
       if(0 > unit) return num;
       unit = Math.pow(10,unit);
       return Math.round(num * unit) / unit; 
    }

    function addZeros(){
       var num = arguments[0],decimalSeparator = arguments[1],precision = arguments[2];
       num = num.split(decimalSeparator);
       void 0 == num[1] && precision > 0 && (num[1] = "0");
       return num[1].length < precision ? (num[1] += "0",this.addZeros(num[0] + decimalSeparator + num[1],decimalSeparator,precision)) : void 0 != num[1] ? num[0] + decimalSeparator + num[1] : num[0];
    }

    function formatNumber(num, format){
       num = roundTo(num,format.precision);
       var decimalSeparator = format.decimalSeparator,
        thousandsSeparator = format.thousandsSeparator,
        isMinus = 0 > num ? '-' : '',
        num = Math.abs(num),
        numStr = num.toString();
       if(numStr.indexOf('e') == -1){
        for(var numArr = numStr.split(decimalSeparator), i = "", k = numArr[0].toString(), j = k.length; 0 <= j; j -= 3){
            i = j != k.length ? 0 != j ? k.substring(j - 3, j) + thousandsSeparator + i : k.substring(j - 3, j) + i : k.substring(j - 3, j);       
                    }
                    numArr[1] && (i = i + decimalSeparator + numArr[1]);
                    format.precision > 0 && "0" != i && (i = addZeros(i,decimalSeparator,format.precision));
        } else{
        i = h;
        } 
        i = isMinus + i;
        return i;  
    }
    
    alert(formatNumber(5.678,{ precision : 2, decimalSeparator : ".", thousandsSeparator : ","}));