-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,709
  • 5
  • 44
  • 66
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,270
  • 8
  • 53
  • 67
Dima Pog
  • 132
  • 4
3

Try this

alert(Math.round(5334.5));

Demo

Amit
  • 15,217
  • 8
  • 46
  • 68
2

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

Math.round(num);
Ruskin
  • 5,721
  • 4
  • 45
  • 62
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,130
  • 1
  • 26
  • 42
1

Use right brackets :

 var result = Math.round(num);

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

Roy M J
  • 6,926
  • 7
  • 51
  • 78
0

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

Chris
  • 2,471
  • 25
  • 36
0

Just modify your codes with this line ::

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