大规模编辑
这个函数会做你想做的事:
function get_meaningful_digit_pos(digits, val1, val2) {
var max = Math.max.apply(null, [val1, val2].map(function(n) {
return Math.abs(n);
})),
digit = Math.pow(10, digits),
index = 0;
// For positive numbers, check how many numbers there are
// before the dot, then return the negative digits left.
if (max > 0) {
while (digit > 1) {
if (max >= digit) {
return -digits;
}
digits--;
digit /= 10;
}
}
// Loop 15 times at max; after that in JavaScript a double
// loses its precision.
for (; index < 15 - digits; index++) {
if (0 + max.toFixed(index) !== 0) {
return index + digits;
}
}
}
它返回您想要的第一个数字的位置,0 是点本身。
以下是我运行的一些测试:
get_meaningful_digit_pos(4, 1234, 0.0); // -3
get_meaningful_digit_pos(4, 12.000001234, 0.0); // -1
get_meaningful_digit_pos(4, 1.234, 0.0); // 0
get_meaningful_digit_pos(4, 0.1234, 1.0); // 0
get_meaningful_digit_pos(4, 0.0000001234, 0.0); // 7
get_meaningful_digit_pos(4, 0.0000001234, 10.0); // -1