Truncate number to two decimal places without rounding

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

    Another single-line solution :

    number = Math.trunc(number*100)/100
    

    I used 100 because you want to truncate to the second digit, but a more flexible solution would be :

    number = Math.trunc(number*Math.pow(10, digits))/Math.pow(10, digits)
    

    where digits is the amount of decimal digits to keep.

    See Math.trunc specs for details and browser compatibility.

提交回复
热议问题