I have a function in JavaScript that rounds numbers.
function roundNumber(num){
var result = Math.round(num*100)/100;
return result;
}
alert(roundNumber(5334.5));
//I still get 5334.5 when normally I should get 5335
What am I missing?
I have a function in JavaScript that rounds numbers.
function roundNumber(num){
var result = Math.round(num*100)/100;
return result;
}
alert(roundNumber(5334.5));
//I still get 5334.5 when normally I should get 5335
What am I missing?
Try to use:
function roundNumber(num){
var result = Math.round(num);
return result;
}
alert(roundNumber(5334.5));
The answer is correct. You are in effect rounding to 2 decimal places. Should be:
Math.round(num);
I think this is one of those times where you want to override the default behaviour, Math.round is a great method but sometimes that wheel just isn't round enough. Here's what you could do:
Math.round = function (x) {
if (parseInt((x + 0.5).toString().split(".")[0], 10) > parseInt(x.toString().split(".")[0], 10)) {
return parseInt((x + 1).toString().split(".")[0], 10);
} else {
return parseInt(x.toString().split(".")[0], 10);
}
};
Just modify your codes with this line ::
var result = Math.round(num);