Truncate number to two decimal places without rounding

Update 5 Nov 2016

New answer, always accurate

function toFixed(num, fixed) {
    var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
    return num.toString().match(re)[0];
}

As floating point math in javascript will always have edge cases, the previous solution will be accurate most of the time which is not good enough. There are some solutions to this like num.toPrecision, BigDecimal.js, and accounting.js. Yet, I believe that merely parsing the string will be the simplest and always accurate.

Basing the update on the well written regex from the accepted answer by @Gumbo, this new toFixed function will always work as expected.


Old answer, not always accurate.

Roll your own toFixed function:

function toFixed(num, fixed) {
    fixed = fixed || 0;
    fixed = Math.pow(10, fixed);
    return Math.floor(num * fixed) / fixed;
}

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.

Tags:

Javascript