Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up to nearest

Tags:

javascript

If the number is 37, I would like it to round to 40, if the number is 1086, I would like it to round to 2000. If the number is 453992, I would like it to round to 500000.

I don't really know how to describe this more generally, sorry, but basically, the number in the highest place should always round up to the nearest digit, and the rest become zeros. I know how to round stuff normally, I just don't know how to cleanly deal with the variation among number of digits.

Thanks,

Edit: I deleted the 4 to 10 round, because that one seemed not to fit with the rest, and its not really necessary.

like image 720
dezman Avatar asked Apr 09 '13 15:04

dezman


People also ask

How do you round up to the nearest decimal?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.

How do I round up to the nearest in Excel?

To always round up (away from zero), use the ROUNDUP function. To always round down (toward zero), use the ROUNDDOWN function. To round a number to a specific multiple (for example, to round to the nearest 0.5), use the MROUND function.

What does it mean with round up to the nearest number?

Rounding to the nearest whole number means converting a number to an approximate value that is easier to use and remember. Usually, decimal numbers and fractions are rounded to the nearest whole number with the help of the appropriate rules.

What does round up to the nearest subject mean?

Rounding to the nearest unit means to find the nearest integer to a given number. Basically, you have to get rid of the decimal part, if any.


2 Answers

Assuming all values are positive integers:

function roundUp(x){

    var y = Math.pow(10, x.toString().length-1);

    x = (x/y);
    x = Math.ceil(x);
    x = x*y;
    return x;
}

Live Demo: http://jsfiddle.net/fP7Z6/

like image 140
Curtis Avatar answered Sep 17 '22 22:09

Curtis


I would use the following function

function specialRoundUp(num) {
    var factor = Math.pow(10, Math.floor(Math.log(num) / Math.LN10));
    return factor * Math.ceil(num/factor);
}
like image 35
halex Avatar answered Sep 18 '22 22:09

halex