3

how to round using ROUND HALF UP in javascript? I am using Prototype JavaScript framework version 1.5.1_rc3, so I prefer to use it if available. If not, I appreciate also if you share it.

Any guidance is appreciated.

eros
  • 4,946
  • 18
  • 53
  • 78
  • You need to explain what rounding you want, there are different kinds. Many (most?) here likely didn't go to a "grade school" with the same curriculum you did so may or may not know what type of rounding you are referring to. – RobG Mar 16 '12 at 02:17

2 Answers2

8

The Math.round() will round up when n >= 5 else round down

Examples:

Math.round(20.49);// 20

Math.round(20.5);// 21

Math.round(-20.5);// -20

Math.round(-20.51);// -21

Note: The examples were taken from the link above

Native functions don't bite, my advice is to try to always try to use them whenever possible. They are faster and do the same job after all

ajax333221
  • 11,436
  • 16
  • 61
  • 95
0

Consider:

if (!Number.prototype.round) {
  Number.prototype.round = function() {
    return Math.round(this);
  }
}

var x = 5.49;
alert(x.round()); // 5
alert((7.499).round()); // 7
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Number is a built–in constructor, adding a method to its prototype means that all numbers inherit the method. Number primitives are converted to Number objects during evaluation of expressions if the expression calls for it. So `5.49` is (more or less) converted to a Number as if `Number(5.49)` had been called, then its `round` method is called, passing the number object as `this`. All standard ECMAScript prototype inheritance. Note that the conversion is only for the sake of evaluating the expression, the value of `x` is still a number primitive. – RobG Mar 16 '12 at 14:12