Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/97.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中避免使用大数字的科学表示法?_Javascript - Fatal编程技术网

如何在JavaScript中避免使用大数字的科学表示法?

如何在JavaScript中避免使用大数字的科学表示法?,javascript,Javascript,当数字变大时,JavaScript将大整数转换为科学符号。如何防止这种情况发生?使用.toPrecision、.toFixed等。您可以通过使用.toString将数字转换为字符串,然后查看其.length来计算数字中的位数,但如果数字大于等于1e21,则使用科学记数法,且最大精度为20。除此之外,你可以自己滚,但会很混乱 function toFixed(x) { if (Math.abs(x) < 1.0) { var e = parseInt(x.toString().s

当数字变大时,JavaScript将大整数转换为科学符号。如何防止这种情况发生?

使用
.toPrecision
.toFixed
等。您可以通过使用
.toString
将数字转换为字符串,然后查看其
.length
来计算数字中的位数,但如果数字大于等于1e21,则使用科学记数法,且最大精度为20。除此之外,你可以自己滚,但会很混乱

function toFixed(x) {
  if (Math.abs(x) < 1.0) {
    var e = parseInt(x.toString().split('e-')[1]);
    if (e) {
        x *= Math.pow(10,e-1);
        x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
    }
  } else {
    var e = parseInt(x.toString().split('+')[1]);
    if (e > 20) {
        e -= 20;
        x /= Math.pow(10,e);
        x += (new Array(e+1)).join('0');
    }
  }
  return x;
}

我对oracle返回科学符号也有同样的问题,但我需要url的实际数字。我只是使用了一个PHP技巧,通过减去零,我得到了正确的数字

例如,5.4987E7是val

newval = val - 0;

newval现在等于54987000

您可以循环数字并实现舍入

//在给定索引处替换字符的功能

//循环数字开始


这就是我最后用来从输入中获取值的方法,将数字扩展到小于17位,并将指数数字转换为x10y

//例如。
//尼斯数字(“1.24e+4”)变为
//1.24x10到4的幂[上标显示]
函数编号(num){
试一试{
var sOut=num.toString();
如果(sOut.length>=17 | | sOut.indexOf(“e”)>0){
sOut=parseFloat(num).toPrecision(5)+;
sOut=sOut.替换(“e”,“x10”)+”;
}
返回sOut;
}
捕获(e){
返回num;
}
}

我知道这是多年以后的事了,但我最近一直在研究一个类似的问题,我想发布我的解决方案。目前被接受的答案用0填充指数部分,我的答案试图找到准确的答案,尽管由于JS在浮点精度方面的限制,一般来说,对于非常大的数字,它并不完全准确

这适用于
Math.pow(2100)
,返回正确的值1267650600228229401496703205376

函数toFixed(x){ var结果=“”; var xStr=x.toString(10); var digitCount=xStr.indexOf('e')=-1?xStr.length:(parseInt(xStr.substr(xStr.indexOf('e')+1))+1); 对于(变量i=1;i 0&&index!==i-1)){ 结果='0'+结果; } 否则{ 结果=模式字符(0)+结果; } } 返回结果; }
console.log(toFixed(Math.pow(2100));//1267650600228229401496703205376对于小数字,如果您知道需要多少位小数,可以使用toFixed,然后使用regexp删除尾随的零

Number(1e-7).toFixed(8).replace(/\.?0+$/,"") //0.000

您可以使用
number.toString(10.1)


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

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

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

以下是我的方法的简短变体,可用于任何数字:

Number.prototype.tofixedsspecial=函数(n){
var str=此.toFixed(n);
如果(str.indexOf('e+')=-1)
返回str;
//若数字采用科学记数法,则选择(b)ase和(p)ower
str=str.replace('.','').split('e+').reduce(函数(b,p){
返回b+数组(p-b.length+2).join(0);
});
如果(n>0)
str+='.'+数组(n+1).join(0);
返回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.tofixedsspecial(3));//“1234567.890”
您的问题:

number :0x68656c6c6f206f72656f
display:4.9299704811152646e+23
您可以使用以下选项:

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

像这样:

let ten =new BigNumber('0x68656c6c6f206f72656f',16);
console.log(ten.toString(10));
display:492997048111526447310191

如果您只是为了显示而这样做,那么可以在数字四舍五入之前从数字构建一个数组

var num = Math.pow(2, 100);
var reconstruct = [];
while(num > 0) {
    reconstruct.unshift(num % 10);
    num = Math.floor(num / 10);
}
console.log(reconstruct.join(''));

其他人的答案并没有给出确切的数字!
此函数精确计算所需的数字并以字符串形式返回,以防止javascript更改它!
如果您需要一个数值结果,只需将函数的结果乘以第一

function toNonExponential(value) {
    // if value is not a number try to convert it to number
    if (typeof value !== "number") {
        value = parseFloat(value);

        // after convert, if value is not a number return empty string
        if (isNaN(value)) {
            return "";
        }
    }

    var sign;
    var e;

    // if value is negative, save "-" in sign variable and calculate the absolute value
    if (value < 0) {
        sign = "-";
        value = Math.abs(value);
    }
    else {
        sign = "";
    }

    // if value is between 0 and 1
    if (value < 1.0) {
        // get e value
        e = parseInt(value.toString().split('e-')[1]);

        // if value is exponential convert it to non exponential
        if (e) {
            value *= Math.pow(10, e - 1);
            value = '0.' + (new Array(e)).join('0') + value.toString().substring(2);
        }
    }
    else {
        // get e value
        e = parseInt(value.toString().split('e+')[1]);

        // if value is exponential convert it to non exponential
        if (e) {
            value /= Math.pow(10, e);
            value += (new Array(e + 1)).join('0');
        }
    }

    // if value has negative sign, add to it
    return sign + value;
}
函数toNonExponential(值){
//如果值不是数字,请尝试将其转换为数字
如果(值的类型!=“编号”){
value=parseFloat(值);
//转换后,如果值不是数字,则返回空字符串
如果(isNaN(值)){
返回“”;
}
}
var符号;
变量e;
//如果值为负,则在符号变量中保存“-”,并计算绝对值
如果(值<0){
符号“-”;
value=Math.abs(值);
}
否则{
符号=”;
}
//如果值介于0和1之间
如果(值<1.0){
//获得e值
e=parseInt(value.toString().split('e-')[1]);
//如果值是指数型的,则将其转换为非指数型
如果(e){
数值*=数学功率(10,e-1);
value='0'.+(新数组(e)).join('0')+value.toString().substring(2);
}
}
否则{
//获得e值
e=parseInt(value.toString().split('e+')[1]);
//如果值是指数型的,则将其转换为非指数型
如果(e){
数值/=数学功率(10,e);
value+=(新数组(e+1)).join('0');
}
}
//若值有负号,则添加到该值
返回符号+值;
}

以下解决方案绕过了非常大和非常小的数字的自动指数格式。这是一个错误修正:它不适用于非常小的负数

函数numberToString(num)
{
设numStr=String(num);
if(数学绝对值(数值)<1.0)
{
设e=parseInt(num.toString().split('e-')[1]);
如果(e)
{
设负=num<0;
如果(负)num*=-1
num*=数学功率(10,e-1);
numStr='0'.+(新数组(e)).join('0')+num.toSt
number :0x68656c6c6f206f72656f
display:4.9299704811152646e+23
let ten =new BigNumber('0x68656c6c6f206f72656f',16);
console.log(ten.toString(10));
display:492997048111526447310191
var num = Math.pow(2, 100);
var reconstruct = [];
while(num > 0) {
    reconstruct.unshift(num % 10);
    num = Math.floor(num / 10);
}
console.log(reconstruct.join(''));
function toNonExponential(value) {
    // if value is not a number try to convert it to number
    if (typeof value !== "number") {
        value = parseFloat(value);

        // after convert, if value is not a number return empty string
        if (isNaN(value)) {
            return "";
        }
    }

    var sign;
    var e;

    // if value is negative, save "-" in sign variable and calculate the absolute value
    if (value < 0) {
        sign = "-";
        value = Math.abs(value);
    }
    else {
        sign = "";
    }

    // if value is between 0 and 1
    if (value < 1.0) {
        // get e value
        e = parseInt(value.toString().split('e-')[1]);

        // if value is exponential convert it to non exponential
        if (e) {
            value *= Math.pow(10, e - 1);
            value = '0.' + (new Array(e)).join('0') + value.toString().substring(2);
        }
    }
    else {
        // get e value
        e = parseInt(value.toString().split('e+')[1]);

        // if value is exponential convert it to non exponential
        if (e) {
            value /= Math.pow(10, e);
            value += (new Array(e + 1)).join('0');
        }
    }

    // if value has negative sign, add to it
    return sign + value;
}
function removeExponent(s) {
    var ie = s.indexOf('e');
    if (ie != -1) {
        if (s.charAt(ie + 1) == '-') {
            // negative exponent, prepend with .0s
            var n = s.substr(ie + 2).match(/[0-9]+/);
            s = s.substr(2, ie - 2); // remove the leading '0.' and exponent chars
            for (var i = 0; i < n; i++) {
                s = '0' + s;
            }
            s = '.' + s;
        } else {
            // positive exponent, postpend with 0s
            var n = s.substr(ie + 1).match(/[0-9]+/);
            s = s.substr(0, ie); // strip off exponent chars            
            for (var i = 0; i < n; i++) {
                s += '0';
            }       
        }
    }
    return s;
}
function dissolveExponentialNotation(number)
{
    if(!Number.isFinite(number)) { return undefined; }

    let text = number.toString();
    let items = text.split('e');

    if(items.length == 1) { return text; }

    let significandText = items[0];
    let exponent = parseInt(items[1]);

    let characters = Array.from(significandText);
    let minus = characters[0] == '-';
    if(minus) { characters.splice(0, 1); }
    let indexDot = characters.reduce((accumulator, character, index) =>
    {
        if(!accumulator.found) { if(character == '.') { accumulator.found = true; } else { accumulator.index++; } }
        return accumulator;
    }, { index: 0, found: false }).index;

    characters.splice(indexDot, 1);

    indexDot += exponent;

    if(indexDot >= 0 && indexDot < characters.length - 1)
    {
        characters.splice(indexDot, 0, '.');
    }
    else if(indexDot < 0)
    {
        characters.unshift("0.", "0".repeat(-indexDot));
    }
    else
    {
        characters.push("0".repeat(indexDot - characters.length));
    }

    return (minus ? "-" : "") + characters.join("");
}
// 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);
const myNumb = 1000000000000000000000;
console.log( myNumb ); // 1e+21
console.log( myNumb.toLocaleString() ); // "1,000,000,000,000,000,000,000"
console.log( myNumb.toLocaleString('fullwide', {useGrouping:false}) ); // "1000000000000000000000"
const myNumb = 586084736227728377283728272309128120398;
console.log( myNumb.toLocaleString('fullwide', { useGrouping: false }) );
import fromExponential from 'from-exponential';

fromExponential(1.123e-10); // => '0.0000000001123'
function printInt(n) { return n.toPrecision(100).replace(/\..*/,""); }
eToNumber("123456789123456789.111122223333444455556666777788889999e+50");
// output:
"12345678912345678911112222333344445555666677778888999900000000000000"
eToNumber("123.456123456789123456895e-80");
// output:
"0.00000000000000000000000000000000000000000000000000000000000000000000000000000123456123456789123456895"
eToNumber("123456789123456789.111122223333444455556666777788889999e-50");
// output:
"0.00000000000000000000000000000000123456789123456789111122223333444455556666777788889999"
123e1   ==> 1230
123E1   ==> 1230
123e+1  ==> 1230
123.e+1 ==> 1230
123e-1  ==> 12.3
0.1e-1  ==> 0.01
.1e-1   ==> 0.01
-123e1  ==> -1230