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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With