Truncate number to two decimal places without rounding

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

    Here you are. An answer that shows yet another way to solve the problem:

    // For the sake of simplicity, here is a complete function:
    function truncate(numToBeTruncated, numOfDecimals) {
        var theNumber = numToBeTruncated.toString();
        var pointIndex = theNumber.indexOf('.');
        return +(theNumber.slice(0, pointIndex > -1 ? ++numOfDecimals + pointIndex : undefined));
    }
    

    Note the use of + before the final expression. That is to convert our truncated, sliced string back to number type.

    Hope it helps!

提交回复
热议问题