使用JavaScript,如何使用.toExponential()函数,但仅使用两个小数位(9.99e9,而不是9.9999e9)

问题描述 投票:0回答:3

如果我有一个设置为2345的变量,并且想要将其转换为指数,我只需执行variableName.toExponential()。replace(/ e +?/,'e'),这将给我2.345e3。但是,我希望它只返回两个小数位,因为否则,一旦获得更大的数字(如183947122),我将得到一个长的小数1.83947122e8。我希望将其降低到1.83e8,但是我不知道在此代码中将variable.toFixed(2)放在哪里。

javascript decimal exponential floor
3个回答
0
投票

您可以通过重新分析系数并使用toFixed将其限制为两位小数来实现,请参见注释:

let variableName = 2345;
// Get the coefficient and exponent as separate strings
const [coefficient, exponent] = variableName.toExponential().split("e+");
// Limit the coefficient to two decimal places
// and reassemble with your preferred separator
const str = (+coefficient).toFixed(2) + "e" + exponent;
console.log(str);

0
投票

var a=1233434;
console.log(a.toExponential(2));

您可以在.toExponential(2)函数中传递参数进行舍入。在十进制检查后,该链接将给出2个数字https://www.geeksforgeeks.org/javascript-toexponential-function/


0
投票

您可以计算下限值,然后应用toExponential

const f = (x, p) => {
    const l = 10 ** (Math.floor(Math.log10(Math.abs(x))) - p);
    return (Math.floor(x / l) * l).toExponential(p);
}

console.log(f(183947122, 2));
console.log(f(-183947122, 2));
console.log(f(183947122, 4));
© www.soinside.com 2019 - 2024. All rights reserved.