gpt4 book ai didi

javascript - 当科学记数法超出 toPrecision 范围时怎么办

转载 作者:行者123 更新时间:2023-11-28 06:37:24 29 4
gpt4 key购买 nike

我想在网站上显示一些现在以科学计数法表示的数字。我正在使用 toPrecision 显示数字的正常表示法。

不幸的是,toPrecision 只适用于 1e-6 到 1e20 的范围,而我确实有 1e-7 和 1e-10 这样的数字。

那么当 toPrecision 没有完成我希望它完成的工作时我该怎么办?

我尝试使用 Number() 和 parseFloat() 甚至两者都尝试让这个数字以正常表示法显示......

var min =  1e7,
nr1 = parseFloat(Number(min).toPrecision()),
nr2 = Number(min).toPrecision(),
nr3 = min.toPrecision(),
nr4 = min.toString();

console.log(nr1); //1e-7
console.log(nr2); //1e-7
console.log(nr3); //1e-7
console.log(nr4); //1e-7

到目前为止没有任何效果。

任何帮助将不胜感激

最佳答案

所以我找不到真正的解决方案。我知道 toFixed() 确实有效,但是您需要给出您想要接收的总位数。

每个示例:

 var nr = 1e-7;     
console.log(nr.toFixed(10)) //=> 0.0000001000

这也不太好看到。所以这个脚本确实有效。然而 Javascript 可能会再次搞砸。在每个例子中,我使用 D3 创建一个图表,尽管数字以正常表示法输入,但它会以科学形式再次出现......所以它非常脆弱...

function newToFixed(nr) {
arr1 = (""+nr).split("e"),
arr2 = [],
fixedPos = null;

//notation is already normalized
if (arr1.length === 1) {
return nr;
}

/**
* remove the + or - from the number
* now have the exact number digits we want to use in toFixed
*/
if (arr1[1].indexOf("+") === 0) {
arr2 = arr1[1].split("+");
} else {
arr2 = arr1[1].split("-");
}

//making sure it is a number and not a string
fixedPos = Number(arr2[1]);
return nr.toFixed(fixedPos); //returns 0.0000001
}

关于javascript - 当科学记数法超出 toPrecision 范围时怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34151493/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com