Round to the nearest

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

I really don’t know how to describe it more generally, sorry, but basically the number in the highest place should always be rounded to the nearest digit, and the rest should be zeros. I know how to beat things normally, I just don’t know how to deal with the change in the number of digits.

Thanks,

Edit: I deleted 4-10 rounds because this one did not seem to fit the rest and it was not necessary.

+6
source share
6 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/

+7
source

My fashionable version, which works correctly with decimals and negative numbers and correctly rounds to the nearest to ten, as requested by OP:

 roundToNearestPow(value) { var digits = Math.ceil(Math.log10(Math.abs(value) + 1)); var pow = Math.pow(10, digits - 1); return Math.round(value / pow) * pow; } // roundToNearestPow(-1499.12345) => 1000 // roundToNearestPow( 1500.12345) => 2000 
+3
source

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); } 
+2
source

Get the length of the original number:

 var num; var count = num.toString().length; 

Get the first number:

 var first = num.toString().substring(0, 1); 

Then just ++ first and add count-1 zeros

From the comments

Make sure the number is not a product of 10:

 if((num % 10) != 0) { //do all above in this closure } 
0
source

I read it as the nearest integer, which is production of an integer and some power of 10

You can get it

 var myCeil = function(num){ var power = Math.log(num,10) * Math.LOG10E; var head = Math.floor(power); var rest = power - orig; return Math.ceil(Math.pow(10,next))*Math.pow(10,orig); } i = [37, 1086, 453992]; console.log( i.map(myCeil) ); // -> [ 40, 2000, 500000 ] 

This should also work with non-integer input.

0
source

If you want to round to the nearest power of 10, try this one (javascript)

 function Round2NearestPowerOf10(x) { x = Math.round(x); var strLen = x.toString().length; var y = x / Math.pow(10, strLen); var rst = Math.pow(10, strLen - 1 + Math.round(y)); return rst < 10 ? 10 : rst; } 

The result will be rounded to 10 100 000, etc.

0
source

All Articles