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


当前回答

我有同样的问题与甲骨文返回科学符号,但我需要一个url的实际数字。我只是用了一个PHP技巧减去0,得到了正确的数字。

例如,5.4987E7是val。

newval = val - 0;

Newval现在等于54987000

其他回答

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

import fromExponential from 'from-exponential';

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

这对我没有帮助:

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

但这:

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

我想可能有几个类似的答案,但我想到了一个

// If you're gonna tell me not to use 'with' I understand, just,
// it has no other purpose, ;( andthe code actually looks neater
// 'with' it but I will edit the answer if anyone insists
var commas = false;

function digit(number1, index1, base1) {
    with (Math) {
        return floor(number1/pow(base1, index1))%base1;
    }
}

function digits(number1, base1) {
    with (Math) {
        o = "";
        l = floor(log10(number1)/log10(base1));
        for (var index1 = 0; index1 < l+1; index1++) {
            o = digit(number1, index1, base1) + o;
            if (commas && i%3==2 && i<l) {
                o = "," + o;
            }
        }
        return o;
    }
}

// Test - this is the limit of accurate digits I think
console.log(1234567890123450);

注意:这只与javascript数学函数一样准确,并且在for循环之前的行上使用log而不是log10时存在问题;它会把1000以10为底数写成10000,所以我把它改成了log10,因为大多数人都会用10为底数。

这可能不是一个非常准确的解决方案,但我很自豪地说,它可以成功地跨基数转换数字,并提供了一个逗号选项!

下面是我的短变体的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 toPlainString(num) { return (''+ +num).replace(/(-?)(\d*)\.?(\d*)e([+-]\d+)/, function(a,b,c,d,e) { return e < 0 ? b + '0.' + Array(1-e-c.length).join(0) + c + d : b + c + d + Array(e-d.length+1).join(0); }); } console.log(toPlainString(12345e+12)); console.log(toPlainString(12345e+24)); console.log(toPlainString(-12345e+24)); console.log(toPlainString(12345e-12)); console.log(toPlainString(123e-12)); console.log(toPlainString(-123e-12)); console.log(toPlainString(-123.45e-56)); console.log(toPlainString('1e-8')); console.log(toPlainString('1.0e-8'));