Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refactor this basic code that determines if number is in tens, hundreds, thousands etc

 if (n<100) {
     x = 10;
 } else if (n<1000) {
     x = 100;
 } else if (n<10000) {
     x = 1000;
 } else if (n....

etc. etc.

Is there a nice concise, scalable method for this type of problem? My brain has decided to stop working.

like image 425
Peter Kelly Avatar asked Dec 21 '22 11:12

Peter Kelly


1 Answers

var x = Math.pow( 10, Math.floor( Math.log(n) / Math.log(10) ) );

This one might be preferable, because it's available as a constant so it doesn't need to be calculated each time:

var x = Math.pow( 10, Math.floor( Math.log(n) / Math.LN10 ) );

It basically comes down to rounding down logarithmically.


Edit: Because a combination of log and / often tends to result in errors, it might be a good idea to round the quotient as well (currently, Math.log(1000) / Math.LN10 === 2.9999999999999996).

var x = Math.pow( 10, Math.floor( Math.round( Math.log(1000) / Math.LN10 * 1e10 ) / 1e10 ) );

This rounding might result in new errors, but for 'normal' inputs the answer is now more often correct.

like image 182
pimvdb Avatar answered Dec 24 '22 02:12

pimvdb