Truncate number to two decimal places without rounding

前端 未结 30 3133
再見小時候
再見小時候 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:42

    Roll your own toFixed function: for positive values Math.floor works fine.

    function toFixed(num, fixed) {
        fixed = fixed || 0;
        fixed = Math.pow(10, fixed);
        return Math.floor(num * fixed) / fixed;
    }
    

    For negative values Math.floor is round of the values. So you can use Math.ceil instead.

    Example,

    Math.ceil(-15.778665 * 10000) / 10000 = -15.7786
    Math.floor(-15.778665 * 10000) / 10000 = -15.7787 // wrong.
    

提交回复
热议问题