当在字符串上下文中使用时,JavaScript将超过21位的整数转换为科学符号。我打印了一个整数作为URL的一部分。我怎样才能阻止这种转变的发生?


当前回答

你可以用从指数模块。它是轻量级的,并且经过了充分的测试。

import fromExponential from 'from-exponential';

fromExponential(1.123e-10); // => '0.0000000001123'

其他回答

使用。toprecprecision, . tofixed等。您可以通过将数字转换为. tostring的字符串,然后查看其.length来计算数字中的位数。

你可以使用number.toString(10.1):

console.log(Number.MAX_VALUE.toString(10.1));

注意:这目前适用于Chrome,但不适用于Firefox。规范规定基数必须是整数,所以这会导致不可靠的行为。

如果你不介意使用Lodash,它必须使用toSafeInteger()

_.toSafeInteger(3.2);
// => 3
 
_.toSafeInteger(Number.MIN_VALUE);
// => 0
 
_.toSafeInteger(Infinity);
// => 9007199254740991
 
_.toSafeInteger('3.2');
// => 3

下面是我的短变体的number .prototype. tofixed方法,适用于任何数字:

Number.prototype.toFixedSpecial = function(n) { var str = this.toFixed(n); if (str.indexOf('e+') === -1) return str; // if number is in scientific notation, pick (b)ase and (p)ower str = str.replace('.', '').split('e+').reduce(function(b, p) { return b + Array(p - b.length + 2).join(0); }); if (n > 0) str += '.' + Array(n + 1).join(0); return str; }; console.log( 1e21.toFixedSpecial(2) ); // "1000000000000000000000.00" console.log( 2.1e24.toFixedSpecial(0) ); // "2100000000000000000000000" console.log( 1234567..toFixedSpecial(1) ); // "1234567.0" console.log( 1234567.89.toFixedSpecial(3) ); // "1234567.890"

还有一个可能的解决方案:

function toFix(i){
 var str='';
 do{
   let a = i%10;
   i=Math.trunc(i/10);
   str = a+str;
 }while(i>0)
 return str;
}