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


当前回答

这对我没有帮助:

console.log( myNumb.toLocaleString('fullwide', {useGrouping:false}) );

但这:

value.toLocaleString("fullwide", { 
   useGrouping: false, 
   maximumSignificantDigits: 20,
})

其他回答

下面是我的短变体的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"

你的问题:

number :0x68656c6c6f206f72656f
display:4.9299704811152646e+23

你可以使用这个:https://github.com/MikeMcl/bignumber.js

用于任意精度的十进制和非十进制算术的JavaScript库。

是这样的:

let ten =new BigNumber('0x68656c6c6f206f72656f',16);
console.log(ten.toString(10));
display:492997048111526447310191
function printInt(n) { return n.toPrecision(100).replace(/\..*/,""); }

有一些问题:

0.9显示为“0” -0.9显示为"-0" 1e100显示为“1” 仅适用于~1e99 =>以下的数字,对于更大的数字使用其他常数;或者更小的优化。

你也可以使用YourJS.fullNumber。例如,YourJS.fullNumber(Number.MAX_VALUE)的结果如下: 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

它也适用于非常小的数字。YourJS.fullNumber(Number.MIN_VALUE)返回: 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005

重要的是要注意,这个函数总是返回有限的数字作为字符串,但会返回非有限的数字(例如。NaN或无穷大)作为未定义的。

你可以在YourJS控制台进行测试。

这对我没有帮助:

console.log( myNumb.toLocaleString('fullwide', {useGrouping:false}) );

但这:

value.toLocaleString("fullwide", { 
   useGrouping: false, 
   maximumSignificantDigits: 20,
})