javascript 中的小数

Decimals in javascript

如何在 javascript 中转换此输出:

a = 1.0000006

b = 0.00005

c = 2.54695621e-7

到此输出:

a = 1

b = 5e-5

c = 2.547e-7

试试下面的代码:

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);

有了这个输入:

var nums = [1.0000006, 0.00005, 2.54695621e-7];

你可以使用Number#toExponential得到具有一定精度的指数表示法:

function formatNumber(n) {
    return n.toExponential(3);
}

nums.map(formatNumber)
// ["1.000e+0", "5.000e-5", "2.547e-7"]

将它分成有用的部分:

function formatNumber(n) {
    return n
        .toExponential(3)
        .split(/[.e]/);
}

nums.map(formatNumber)
// [["1", "000", "+0"], ["5", "000", "-5"], ["2", "547", "-7"]]

和trim去掉不必要的:

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"]

ES6:

const formatNumber = n => {
    const [, integral, fractional, exponent] =
        /(\d+)(\.\d+)(e.\d+)/.exec(n.toExponential(3));

    return integral +
        fractional.replace(/\.?0+$/, '') +
        (exponent === 'e+0' ? '' : exponent);
};