-6

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?

Demo: http://jsfiddle.net/HwvX2/

Jamie Taylor
  • 4,661
  • 5
  • 42
  • 62
Mando Madalin
  • 193
  • 2
  • 3
  • 14
  • You're dividing the result by 100. Why are you expecting that to be an integer? – Bugs Feb 06 '14 at 11:26
  • Your function is a way to truncate to 2 decimal places, but you are expecting to get it to round to the nearest whole number. Bit of a logical error here. – Paddy Feb 06 '14 at 11:28
  • You appear to be using code from http://stackoverflow.com/questions/11832914/round-up-to-2-decimal-places-in-javascript which rounds to two decimal places – Ruskin Feb 06 '14 at 11:30

7 Answers7

5

Try to use:

function roundNumber(num){
    var result = Math.round(num);
    return result;
}

alert(roundNumber(5334.5));
Danilo Valente
  • 11,037
  • 8
  • 52
  • 66
Dima Pog
  • 152
  • 4
3

Try this

alert(Math.round(5334.5));

Demo

Amit
  • 15,021
  • 8
  • 44
  • 66
2

The answer is correct. You are in effect rounding to 2 decimal places. Should be:

Math.round(num);
Ruskin
  • 5,232
  • 3
  • 43
  • 60
2

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);
      }
};
Dormouse
  • 5,000
  • 1
  • 25
  • 42
1

Use right brackets :

 var result = Math.round(num);

Demo : http://jsbin.com/tibo/1/

Roy M J
  • 6,856
  • 7
  • 47
  • 77
0

should be Math.round((num*100)/100)

Chris
  • 2,461
  • 24
  • 36
0

Just modify your codes with this line ::

       var result = Math.round(num);
Charles Stevens
  • 1,510
  • 15
  • 29