Search code examples
javascript

Truncate number to two decimal places without rounding


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)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));

Results in -

15.8
15.78
15.778
15.7784514000 

How do I display 15.77?


Solution

  • 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
    }
    <form onsubmit="return calc(this)">
    Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" />
    <br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly>
    </form>

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