Truncate number to two decimal places without rounding

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

    Convert the number into a string, match the number up to the second decimal place:

    function calc(theform) {
        var num = theform.original.value, rounded = theform.rounded
        var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
        rounded.value = with2Decimals
    }
    Original number:
    "Rounded" number:

    The toFixed method fails in some cases unlike toString, so be very careful with it.

提交回复
热议问题