Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round using ROUND HALF UP. Rounding mode that most of us were taught in grade school

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.

like image 800
eros Avatar asked Sep 11 '25 10:09

eros


2 Answers

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

like image 95
ajax333221 Avatar answered Sep 13 '25 00:09

ajax333221


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
like image 31
RobG Avatar answered Sep 12 '25 23:09

RobG