Use JavaScript to round a number to decimal places

Well, you will be glad to know it’s easier than you think. I had no idea but JavaScript comes with a function to do exactly that. Hurrah!

Simply call the inline function and pass it the number of decimal places you want the number to be rounded to. It will automatically work out if it needs to be rounded up or down.

var num = 13.1489;
alert(num.toFixed()) // 13
alert(num.toFixed(1)) // 13.1
alert(num.toFixed(3)) // 13.149
alert(num.toFixed(4)) // 13.1489

// Just remember to cast all strings as a number first!
var num = "15.1568";
alert(Number(num).toFixed(2)) // 15.16