One of the things I love the most about the internet and the search engines is the fact you are able to search and find whatever you need to to, even your own work!. Today I was looking for a Javascript Math roundup function I had used a couple of years ago and Googling the title of small page I had created for my students so they could calculate their marks I found the code I was looking for:

function round(number,X) {

// rounds number to X decimal places, defaults to 2

X = (!X ? 2 : X);
return Math.round(number*Math.pow(10,X))/Math.pow(10,X);

}
As you might remember Javascript allows you to roundup a number to the integer value, but this handy function also gives you the chance to use decimal value. In the university I worked we used to roundup the marks using two decimal numbers so it was useful to embed this formula into my calculator page.


  1. John

    This is NOT a roundup function. It is merely a rounding function. A roundup function always rounds UP, not down. In other words, if the value is 1.34, it would round UP to 2.00, not down to 1.00.

  2. eugene

    Math.round() does not round up … it rounds off …
    .5 and above rounds up while less than .5 rounds down.

    HOWEVER … if you can tell me of a built in function or obj.method that rounds up I would be most pleased.

  3. eugene

    var floatingPointNumber= 1.244;
    var roundedToTwoDecimalPlaces =
    Math.ceil(floatingPointNumber * 100) / 100;

  4. Tim

    thanks

    needed it very badly

  5. Fred Bloggs

    As previously stated this is not a roundup function just a round function. However the other comment did not provide the roundup solution, to round up in Javascript simply use the Math.ceil() function. So passing in 2.12, Math.ceil(2.12) would give the result as 3.

  6. A83

    Math.ceil() will always round up and Math.floor() will always round down.




Leave a Comment