js保留小数点后n位,不四舍五入

function toFixedDigit(num,n){ //保留n位
    if(typeof num != 'number'){ 
        return false;
    };
    if(n <= 0){ //不保留小数,取整
        return num | 0;
    };
    num = num.toString();
    var result = "";
    var zeroResult = function(n){ 
        var zero = "";
        for(var i = 0;i<n;i++){ 
            zero+="0";
        }
        return zero;
    }
    if(num%1 == 0){ //整数
        result = num + "."+zeroResult(n);
    }else{ //小数
        var num1 = num.split(".");
        if(num1[1].length<n){ 
           result = num1[0]+"."+num1[1]+zeroResult(n-num1[1].length)
        }else{ 
           result = num1[0]+"."+num1[1].substring(0,n)
        }
    }
    return result;
}
var result1 = toFixedDigit(8.7,2)
console.log(result1)//8.70
var result2 = toFixedDigit(8,2)
console.log(result2)//8.00
var result3 = toFixedDigit(8.6999,2)
console.log(result3)//8.69
var result4 = toFixedDigit(85.6999765,4)
console.log(result4)//85.6999
    原文作者:前端小哥哥
    原文地址: https://blog.csdn.net/sunzhen15896/article/details/107348202
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞