Parsing and converting exponential values to decimal in JavaScript

前端 未结 8 1559
梦毁少年i
梦毁少年i 2020-12-05 11:19

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

相关标签:
8条回答
  • 2020-12-05 12:17

    Here is my short function code that converts Exponential (e-Notation) Numbers to Decimals, allowing the output of large number of decimal places.

    It handles all the e-notation syntax permitted by Javascript which include the following:

    Valid e-notation numbers in Javascript:
       123e1    ==>  1230
       123E1    ==>  1230
       123e+1   ==>  1230
       123.e+1  ==>  1230   (with missing fractional part)
       123e-1   ==>  12.3
       0.1e-1   ==>  0.01
       .1e-1    ==>  0.01   (with missing whole part)
      -123e1    ==> -1230
       0.0e1    ==>  0
      -0.0e4    ==> -0
    
    

    The function does not attempt to trap NaN or undefined inputs but does attempt to cater for normal (non-e-notation) numbers; such numbers are returned "as is".

    I have tried to provide enough comments on each line and tried to avoid (as far as possible!) the use of short-circuiting and conditional (ternary) operators for better clarity.

    I have used the toLocaleString() method to automatically detect the decimal separator sign, but this, of course, assumes that the input string representing the number follows the machine's locale (especially when manually passed to the function).

    /********************************************************
    * Converts Exponential (e-Notation) Numbers to Decimals
    ********************************************************
    * @function numberExponentToLarge()
    * @version  1.00
    * @param   {string}  Number in exponent format.
    *                   (other formats returned as is).
    * @return  {string}  Returns a decimal number string.
    * @author  Mohsen Alyafei
    * @date    12 Jan 2020
    *
    * Notes: No check is made for NaN or undefined inputs
    *
    *******************************************************/
    
    function numberExponentToLarge(numIn) {
     numIn +="";                                            // To cater to numric entries
     var sign="";                                           // To remember the number sign
     numIn.charAt(0)=="-" && (numIn =numIn.substring(1),sign ="-"); // remove - sign & remember it
     var str = numIn.split(/[eE]/g);                        // Split numberic string at e or E
     if (str.length<2) return sign+numIn;                   // Not an Exponent Number? Exit with orginal Num back
     var power = str[1];                                    // Get Exponent (Power) (could be + or -)
    
     var deciSp = 1.1.toLocaleString().substring(1,2);  // Get Deciaml Separator
     str = str[0].split(deciSp);                        // Split the Base Number into LH and RH at the decimal point
     var baseRH = str[1] || "",                         // RH Base part. Make sure we have a RH fraction else ""
         baseLH = str[0];                               // LH base part.
    
      if (power>=0) {   // ------- Positive Exponents (Process the RH Base Part)
         if (power> baseRH.length) baseRH +="0".repeat(power-baseRH.length); // Pad with "0" at RH
         baseRH = baseRH.slice(0,power) + deciSp + baseRH.slice(power);      // Insert decSep at the correct place into RH base
          if (baseRH.charAt(baseRH.length-1) ==deciSp) baseRH =baseRH.slice(0,-1); // If decSep at RH end? => remove it
    
      } else {         // ------- Negative exponents (Process the LH Base Part)
         num= Math.abs(power) - baseLH.length;                               // Delta necessary 0's
         if (num>0) baseLH = "0".repeat(num) + baseLH;                       // Pad with "0" at LH
         baseLH = baseLH.slice(0, power) + deciSp + baseLH.slice(power);     // Insert "." at the correct place into LH base
         if (baseLH.charAt(0) == deciSp) baseLH="0" + baseLH;                // If decSep at LH most? => add "0"
    
      }
      // Rremove leading and trailing 0's and Return the long number (with sign)
      return sign + (baseLH + baseRH).replace(/^0*(\d+|\d+\.\d+?)\.?0*$/,"$1");
    }
    
    //============ test codes ==================
    function test(test,input,should){
    var  out=numberExponentToLarge(input);
    var r = (out===should) ? true : false;
    if (!r) console.log(test+" Failed: "+out+" should be: "+should);
      else console.log("Passed");
    }
    // ------------- tests for e-notation numbers ---------------------
    
    test(1,"123E0","123")
    test(2,"123E0","123")
    test(3,"-123e+0","-123")
    test(4,"123e1","1230")
    test(5,"123e3","123000")
    test(6,"123e+3","123000")
    test(7,"123E+7","1230000000")
    test(8,"-123.456e+1","-1234.56")
    test(9,"123.456e+4","1234560")
    test(10,"123E-0","123")
    test(11,"123.456e+50","12345600000000000000000000000000000000000000000000000")
    
    test(12,"123e-0","123")
    test(13,"123e-1","12.3")
    test(14,"123e-3","0.123")
    test(15,"-123e-7","-0.0000123")
    test(16,"123.456E-1","12.3456")
    test(17,"123.456e-4","0.0123456")
    test(18,"123.456e-50","0.00000000000000000000000000000000000000000000000123456")
    test(18-1,"-123.456e-50","-0.00000000000000000000000000000000000000000000000123456")
    
    test(19,"1.e-5","0.00001")  // handle missing base fractional part
    test(20,".123e3","123")     // handle missing base whole part
    
    // The Electron's Mass: 
    test(21,"9.10938356e-31","0.000000000000000000000000000000910938356")
    // The Earth's Mass:
    test(22,"5.9724e+24","5972400000000000000000000")
    // Planck constant:
    test(23,"6.62607015e-34","0.000000000000000000000000000000000662607015")
    
    test(24,"0.000e3","0")
    test(25,"0.000000000000000e3","0")
    test(26,"-0.0001e+9","-100000")
    test(27,"-0.0e1","-0")
    test(28,"-0.0000e1","-0")
    test(28,"-000.0000e1","-0")    // this is an invalid Javascript number
    test(28,"-000.0000e-1","-0")   // this is an invalid Javascript number
    test(28,"-000.0000e+10","-0")  // this is an invalid Javascript number
    test(28,"-000.0000e+2","-0")   // this is an invalid Javascript number
    
    // ------------- testing for Non e-Notation Numbers -------------
    test(29,"12345.7898","12345.7898") // no exponent
    test(30,12345.7898,"12345.7898")   // no exponent
    test(31,0.00000000000001,"0.00000000000001")    // from 1e-14
    test(32,-0.0000000000000345,"-0.0000000000000345") // from -3.45e-14
    test(33,-0,"0")
    test(34,"1.2000e0","1.2")
    test(35,"1.2000e-0","1.2")
    test(35,"1.2000e+0","1.2")
    test(35,"1.2000e+10","12000000000")

    0 讨论(0)
  • 2020-12-05 12:17

    Use toFixed(number)

    eg :

    (+exponentialnumber).toFixed(8)
    
    
    2e-7 ===> 0.00000020
    
    0 讨论(0)
提交回复
热议问题