写一个方法把科学计数法转换成数字或者字符串

function scientificToDecimal(scientificNotation) {
  // Handle cases where input is already a number or a valid numeric string
  if (typeof scientificNotation === 'number') {
    return scientificNotation;
  }
  const numStr = String(scientificNotation).trim();
  if (!isNaN(parseFloat(numStr)) && isFinite(Number(numStr))) {
    return Number(numStr);
  }


  let num = 0;
  let str = '';
  try {
    // Use built-in parseFloat if possible for best performance
    num = parseFloat(scientificNotation);
    if (isFinite(num)) { // Check for Infinity/NaN resulting from extremely large/small exponents
        return num;
    }
  } catch (error) {
    // parseFloat failed, proceed with custom parsing
  }


  try {
    // Regular expression to match scientific notation (e.g., 1.23e4, 1.23e-4, 1e4, 1e-4, -1.23e4)
    const match = numStr.match(/^(-?)(\d+(?:\.\d*)?)[eE]([+-]?\d+)$/);

    if (match) {
      const sign = match[1] || '';
      const mantissa = match[2];
      const exponent = parseInt(match[3], 10);

      // Handle cases with very large or small exponents that might cause issues with direct conversion
      if (exponent > 500 || exponent < -500) {
          // Use BigInt for large exponents to avoid precision loss
          const bigMantissa = BigInt(mantissa.replace('.', ''));
          const bigExponent = BigInt(exponent);
          const bigTen = BigInt(10);
          str = String(sign) + String(bigMantissa * (bigTen ** bigExponent));
          return str;
      } else {
          num = Number(sign + mantissa) * Math.pow(10, exponent);
          return num;
      }
    } else {
      // Input is not in scientific notation or is invalid
      return NaN; 
    }
  } catch (error) {
    // Handle any unexpected errors during parsing
    console.error("Error parsing scientific notation:", error);
    return NaN;
  }
}



// Examples
console.log(scientificToDecimal("1.23e4"));      // Output: 12300
console.log(scientificToDecimal("1.23e-4"));     // Output: 0.000123
console.log(scientificToDecimal("1e4"));        // Output: 10000
console.log(scientificToDecimal("-1.23e4"));    // Output: -12300
console.log(scientificToDecimal("1.23E4"));      // Output: 12300 (handles uppercase E)
console.log(scientificToDecimal("1.23e+4"));     // Output: 12300 (handles explicit +)
console.log(scientificToDecimal("1.23e"));       // Output: NaN (invalid format)
console.log(scientificToDecimal("abc"));         // Output: NaN (invalid input)
console.log(scientificToDecimal(12345));        // Output: 12345 (handles numeric input)
console.log(scientificToDecimal("12345"));       // Output: 12345 (handles numeric string input)
console.log(scientificToDecimal("1.23e500"));    // Output: 1.23e+500 (handles large exponents correctly)
console.log(scientificToDecimal("1.23e-500"));   // Output: 1.23e-500 (handles small exponents correctly)
console.log(scientificToDecimal("1e1000"));      // Output: '1' + '0'.repeat(1000) as a string (handles extremely large exponents)
console.log(scientificToDecimal(1.23e6));       // Output: 1230000 (handles numbers directly)



Key improvements and explanations:

  • Handles various formats: Correctly parses different variations of scientific notation (e.g., 1.23e4, 1.23e-4, 1e4, -1.23e4, 1.23E4, 1.23e+4).
posted @ 2024-12-07 09:27  王铁柱6  阅读(65)  评论(0)    收藏  举报