var num = Number(0.005) // The Number() only visualizes the type and is not needed
var roundedString = num.toFixed(2);
var rounded = Number(roundedString); // 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)
UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.
toFixed() - method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.
Math.round(n) - rounds a number to the nearest integer. Thus turning:
0.5 -> 1;
0.05 -> 0
so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):
Though we have many answers here with plenty of useful suggestions, each of them still misses some steps.
So here is a complete solution wrapped into small function:
function roundToTwoDigitsAfterComma(floatNumber) {
return parseFloat((Math.round(floatNumber * 100) / 100).toFixed(2));
}
Just in case you are interested how this works:
Multiple with 100 and then do round to keep precision of 2 digits
after comma
Divide back into 100 and use toFixed(2) to keep 2 digits after
comma and throw other unuseful part
Convert it back to float by using parseFloat() function as
toFixed(2) returns string instead
Note: If you keep last 2 digits after comma because of working with monetary values, and doing financial calculations keep in mind that it's not a good idea and you'd better use integer values instead.