Truncate number to two decimal places without rounding

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

    These solutions do work, but to me seem unnecessarily complicated. I personally like to use the modulus operator to obtain the remainder of a division operation, and remove that. Assuming that num = 15.7784514:

    num-=num%.01;
    

    This is equivalent to saying num = num - (num % .01).

提交回复
热议问题