重构这个确定数字是十、百、千等的基本代码 [英] 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....
等等.等
对于此类问题,是否有一种简洁、可扩展的方法?我的大脑决定停止工作.
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.
编辑:由于 log
和 /
的组合通常会导致错误,因此将商四舍五入可能是个好主意以及(目前,Math.log(1000)/Math.LN10 === 2.9999999999999996
).
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.
这篇关于重构这个确定数字是十、百、千等的基本代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!