在 JavaScript 中解析指数值并将其转换为十进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18719775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:58:50  来源:igfitidea点击:

Parsing and converting exponential values to decimal in JavaScript

javascript

提问by SharpCoder

I want to parse and convert an exponential value into a decimal using JavaScript. 4.65661287307739E-10should give 0.000000000465661287307739. What should I do to achieve this?

我想使用 JavaScript 解析指数值并将其转换为小数。4.65661287307739E-10应该给0.000000000465661287307739。我应该怎么做才能实现这一目标?

parseFloat(4.65661287307739E-10)returns 4.65661287307739e-10.

parseInt(4.65661287307739E-10)returns 4.

parseFloat(4.65661287307739E-10)返回4.65661287307739e-10

parseInt(4.65661287307739E-10)返回4

回答by kennebec

You can display the stringvalue of a large or small decimal:

您可以显示大或小十进制的字符串值:

Number.prototype.noExponents= function(){
    var data= String(this).split(/[eE]/);
    if(data.length== 1) return data[0]; 

    var  z= '', sign= this<0? '-':'',
    str= data[0].replace('.', ''),
    mag= Number(data[1])+ 1;

    if(mag<0){
        z= sign + '0.';
        while(mag++) z += '0';
        return z + str.replace(/^\-/,'');
    }
    mag -= str.length;  
    while(mag--) z += '0';
    return str + z;
}
var n=4.65661287307739E-10 ;
n.noExponents()

/*  returned value: (String)
0.000000000465661287307739
*/

回答by Gray

You can use toFixed(), but there is a limit of 20.

您可以使用toFixed(),但限制为 20。

ex:

前任:

(4.65661287307739E-10).toFixed(20)
"0.00000000046566128731"

But...

但...

(4.65661287307739E-30).toFixed(20)
"0.00000000000000000000"

So if you always have fewer than 20 decimal places, you'll be fine. Otherwise, I think you may have to write your own.

因此,如果您的小数位始终少于 20 位,您会没事的。否则,我认为您可能必须自己编写。

回答by ibrahim tanyalcin

A horribly primitive conversion, written with ES6:

一个可怕的原始转换,用 ES6 编写:

function convert(n){
    var [lead,decimal,pow] = n.toString().split(/e|\./);
    return +pow <= 0 
        ? "0." + "0".repeat(Math.abs(pow)-1) + lead + decimal
        : lead + ( +pow >= decimal.length ? (decimal + "0".repeat(+pow-decimal.length)) : (decimal.slice(0,+pow)+"."+decimal.slice(+pow)))
}

var myvar = 4.951760157141521e+27;
var myvar2 = 4.951760157141521e-2;
convert(myvar);//"4951760157141521000000000000"
convert(myvar2);//"0.04951760157141521"

回答by Alex Gongadze

This variant works well for me to display formatted string values for too small/big numbers:

这个变体非常适合我显示太小/大数字的格式化字符串值:

const exponentialToDecimal = exponential => {
    let decimal = exponential.toString().toLowerCase();
    if (decimal.includes('e+')) {
        const exponentialSplitted = decimal.split('e+');
        let postfix = '';
        for (
            let i = 0;
            i <
            +exponentialSplitted[1] -
                (exponentialSplitted[0].includes('.') ? exponentialSplitted[0].split('.')[1].length : 0);
            i++
        ) {
            postfix += '0';
        }
        const addCommas = text => {
            let j = 3;
            let textLength = text.length;
            while (j < textLength) {
                text = `${text.slice(0, textLength - j)},${text.slice(textLength - j, textLength)}`;
                textLength++;
                j += 3 + 1;
            }
            return text;
        };
        decimal = addCommas(exponentialSplitted[0].replace('.', '') + postfix);
    }
    if (decimal.toLowerCase().includes('e-')) {
        const exponentialSplitted = decimal.split('e-');
        let prefix = '0.';
        for (let i = 0; i < +exponentialSplitted[1] - 1; i++) {
            prefix += '0';
        }
        decimal = prefix + exponentialSplitted[0].replace('.', '');
    }
    return decimal;
};

const result1 = exponentialToDecimal(5.6565e29); // "565,650,000,000,000,000,000,000,000,000"
const result2 = exponentialToDecimal(5.6565e-29); // "0.000000000000000000000000000056565"

回答by Philip Kahn

Expanded from @kennebec 's answer, but handles the edge cases his fails at better (Gist, with CoffeeScript):

扩展自 @kennebec 的答案,但可以更好地处理他失败的边缘情况(Gist,使用 CoffeeScript):

  String.prototype.noExponents = function(explicitNum) {
    var data, leader, mag, multiplier, num, sign, str, z;
    if (explicitNum == null) {
      explicitNum = true;
    }

    /*
     * Remove scientific notation from a number
     *
     * After
     * http://stackoverflow.com/a/18719988/1877527
     */
    data = this.split(/[eE]/);
    if (data.length === 1) {
      return data[0];
    }
    z = "";
    sign = this.slice(0, 1) === "-" ? "-" : "";
    str = data[0].replace(".", "");
    mag = Number(data[1]) + 1;
    if (mag <= 0) {
      z = sign + "0.";
      while (!(mag >= 0)) {
        z += "0";
        ++mag;
      }
      num = z + str.replace(/^\-/, "");
      if (explicitNum) {
        return parseFloat(num);
      } else {
        return num;
      }
    }
    if (str.length <= mag) {
      mag -= str.length;
      while (!(mag <= 0)) {
        z += 0;
        --mag;
      }
      num = str + z;
      if (explicitNum) {
        return parseFloat(num);
      } else {
        return num;
      }
    } else {
      leader = parseFloat(data[0]);
      multiplier = Math.pow(10, parseInt(data[1]));
      return leader * multiplier;
    }
  };

  Number.prototype.noExponents = function() {
    var strVal;
    strVal = String(this);
    return strVal.noExponents(true);
  };

回答by Nandkumar Tekale

In ExtJS you can use Ext.Number.toFixed(value, precision)method which internally uses toFixed()method,

在 ExtJS 中,您可以使用Ext.Number.toFixed(value, precision)内部使用toFixed()方法的方法,

E.g.

例如

console.log(Ext.Number.toFixed(4.65661287307739E-10, 10));  
// O/p => 0.0000000005

console.log(Ext.Number.toFixed(4.65661287307739E-10, 15));  
// 0.000000000465661