Truncate number to two decimal places without rounding

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

    I opted to write this instead to manually remove the remainder with strings so I don't have to deal with the math issues that come with numbers:

    num = num.toString(); //If it's not already a String
    num = num.slice(0, (num.indexOf("."))+3); //With 3 exposing the hundredths place
    Number(num); //If you need it back as a Number
    

    This will give you "15.77" with num = 15.7784514;

提交回复
热议问题