I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1
var quantity = 12;
var import1 = 12.55;
var total = quantity * import1;
var answer = parseFloat(total).toFixed(2);
document.write(answer);
A much more generic solution for rounding to N places
function roundN(num,n){
return parseFloat(Math.round(num * Math.pow(10, n)) /Math.pow(10,n)).toFixed(n);
}
console.log(roundN(1,2))
console.log(roundN(1.34,2))
console.log(roundN(1.35,2))
console.log(roundN(1.344,2))
console.log(roundN(1.345,2))
console.log(roundN(1.344,3))
console.log(roundN(1.345,3))
console.log(roundN(1.3444,3))
console.log(roundN(1.3455,3))
Output
1.00
1.34
1.35
1.34
1.35
1.344
1.345
1.344
1.346
Try below code:
function numberWithCommas(number) {
var newval = parseFloat(Math.round(number * 100) / 100).toFixed(2);
return newval.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
For the most accurate rounding, create this function:
function round(value, decimals) {
return Number(Math.round(value +'e'+ decimals) +'e-'+ decimals).toFixed(decimals);
}
and use it to round to 2 decimal places:
console.log("seeked to " + round(1.005, 2));
> 1.01
Thanks to Razu, this article, and MDN's Math.round reference.
here is another solution to round only using floor, meaning, making sure calculated amount won't be bigger than the original amount (sometimes needed for transactions):
Math.floor(num* 100 )/100;
(num + "").replace(/^([0-9]*)(\.[0-9]{1,2})?.*$/,"$1$2")