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?
I use this:
function round(value, precision) {
if(precision == 0)
return Math.round(value);
exp = 1;
for(i=0;i<precision;i++)
exp *= 10;
return Math.round(value*exp)/exp;
}
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:
toFixed(2)
to keep 2 digits after
comma and throw other unuseful partparseFloat()
function as
toFixed(2)
returns string insteadNote: 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.