如何把科学计数法转换为十进制表示?
本帖最后由 hixon 于 2022-7-12 17:34 编辑将下面的转换方法放到全局代码(init.js)中定义var scientificToDecimal = function (num) {
var nsign = num/Math.abs(num);
//remove the sign
num = Math.abs(num);
//if the number is in scientific notation remove it
if (/\d+\.?\d*e[\+\-]*\d+/i.test(num)) {
var zero = '0',
parts = String(num).toLowerCase().split('e'), //split into coeff and exponent
e = parts.pop(), //store the exponential part
l = Math.abs(e), //get the number of zeros
sign = e / l,
coeff_array = parts.split('.');
if (sign === -1) {
l = l - coeff_array.length;
if (l < 0) {
num = coeff_array.slice(0, l) + '.' + coeff_array.slice(l) + (coeff_array.length === 2 ? coeff_array : '');
}
else {
num = zero + '.' + new Array(l + 1).join(zero) + coeff_array.join('');
}
}
else {
var dec = coeff_array;
if (dec)
l = l - dec.length;
if (l < 0) {
num = coeff_array + dec.slice(0, l) + '.' + dec.slice(l);
} else {
num = coeff_array.join('') + new Array(l + 1).join(zero);
}
}
}
return nsign < 0 ? '-'+num : num;
};
在按钮的onRelease事件方法中进行测试
ui.main.textButton.onRelease = function() {
util.console.log(scientificToDecimal(2.5e25));
util.console.log(scientificToDecimal('1.2e-2'));
util.console.log(scientificToDecimal('-1.123e-10'));
util.console.log(scientificToDecimal(-1e-3));
util.console.log(scientificToDecimal(12.12));
util.console.log(scientificToDecimal('0'));
};
测试结果:
页:
[1]