Rounding numbers to 2 digits after comma

Sten Van den Bergh picture Sten Van den Bergh · Nov 4, 2010 · Viewed 218.9k times · Source

I have no idea how to do this? I'm adding comma numbers, result is of course always a number with way too many digits after the comma. anyone?

Answer

Jacob Relkin picture Jacob Relkin · Nov 4, 2010

EDIT 2:

Use the Number object's toFixed method like this:

var num = Number(0.005) // The Number() only visualizes the type and is not needed
var roundedString = num.toFixed(2);
var rounded = Number(roudedString); // toFixed() returns a string (often suitable for printing already)

It rounds 42.0054321 to 42.01

It rounds 0.005 to 0.01

It rounds -0.005 to -0.01 (So the absolute value increases on rounding at .5 border)

jsFiddle example