如何在javascript中转换此输出:
a = 1.0000006
b = 0.00005
c = 2.54695621e-7
到这个输出:
a = 1
b = 5e-5
c = 2.547e-7
答案 0 :(得分:0)
请尝试以下代码:
var a = 1.0000006;
var b = 0.00005;
var c = 2.54695621e-7;
var a_Result = Math.round(a);
var b_Result = b.toExponential();
var c_Result = c.toExponential(3);
console.log(a_Result );
console.log(b_Result);
console.log(c_Result);

答案 1 :(得分:0)
使用此输入:
function formatNumber(n) {
return n.toExponential(3);
}
nums.map(formatNumber)
// ["1.000e+0", "5.000e-5", "2.547e-7"]
您可以使用Number#toExponential
以一定的精度获得指数表示法:
function formatNumber(n) {
return n
.toExponential(3)
.split(/[.e]/);
}
nums.map(formatNumber)
// [["1", "000", "+0"], ["5", "000", "-5"], ["2", "547", "-7"]]
将其分成有用的部分:
function formatNumber(n) {
var parts = n
.toExponential(3)
.split(/[.e]/);
var integral = parts[0];
var fractional = '.' + parts[1];
var exponent = 'e' + parts[2];
fractional = fractional.replace(/\.?0+$/, '');
exponent = exponent === 'e+0' ? '' : exponent;
return integral + fractional + exponent;
}
nums.map(formatNumber)
// ["1", "5e-5", "2.547e-7"]
并修剪掉不必要的东西:
const formatNumber = n => {
const [, integral, fractional, exponent] =
/(\d+)(\.\d+)(e.\d+)/.exec(n.toExponential(3));
return integral +
fractional.replace(/\.?0+$/, '') +
(exponent === 'e+0' ? '' : exponent);
};
ES6:
App