科学记数法超出 toPrecision 范围怎么办
What to do when scientific notation exceeds the toPrecision range
我想在网站上显示一些现在采用科学记数法的数字。我正在使用 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
}
我想在网站上显示一些现在采用科学记数法的数字。我正在使用 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
}