Truncate number to two decimal places without rounding

前端 未结 30 2750
再見小時候
再見小時候 2020-11-22 09:08

Suppose I have a value of 15.7784514, I want to display it 15.77 with no rounding.

var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+\"
30条回答
  •  醉酒成梦
    2020-11-22 09:43

    truncate without zeroes

    function toTrunc(value,n){  
        return Math.floor(value*Math.pow(10,n))/(Math.pow(10,n));
    }
    

    or

    function toTrunc(value,n){
        x=(value.toString()+".0").split(".");
        return parseFloat(x[0]+"."+x[1].substr(0,n));
    }
    

    test:

    toTrunc(17.4532,2)  //17.45
    toTrunc(177.4532,1) //177.4
    toTrunc(1.4532,1)   //1.4
    toTrunc(.4,2)       //0.4
    

    truncate with zeroes

    function toTruncFixed(value,n){
        return toTrunc(value,n).toFixed(n);
    }
    

    test:

    toTrunc(17.4532,2)  //17.45
    toTrunc(177.4532,1) //177.4
    toTrunc(1.4532,1)   //1.4
    toTrunc(.4,2)       //0.40
    

提交回复
热议问题