* Convert the given scientific notation to the 'expanded' decimal notation * * @example scientificToDecimal('-123.4567e-6') returns '-0.0001234567' * * @param {number|string} val * @returns {number|string}
(val)
| 1566 | * @returns {number|string} |
| 1567 | */ |
| 1568 | static scientificToDecimal(val) { |
| 1569 | // Check that the val is a Number |
| 1570 | const numericValue = Number(val); |
| 1571 | if (isNaN(numericValue)) { |
| 1572 | return NaN; |
| 1573 | } |
| 1574 | |
| 1575 | // Check if the number is in a scientific notation |
| 1576 | val = String(val); |
| 1577 | const isScientific = this.contains(val, 'e') || this.contains(val, 'E'); |
| 1578 | |
| 1579 | if (!isScientific) { |
| 1580 | return val; |
| 1581 | } |
| 1582 | |
| 1583 | // Convert the scientific notation to a numeric string |
| 1584 | let [value, exponent] = val.split(/e/i); |
| 1585 | const isNegative = value < 0; |
| 1586 | if (isNegative) { |
| 1587 | value = value.replace('-', ''); |
| 1588 | } |
| 1589 | |
| 1590 | const isNegativeExponent = +exponent < 0; |
| 1591 | if (isNegativeExponent) { |
| 1592 | exponent = exponent.replace('-', ''); // Remove the negative sign |
| 1593 | } |
| 1594 | |
| 1595 | const [int, float] = value.split(/\./); |
| 1596 | |
| 1597 | let result; |
| 1598 | if (isNegativeExponent) { |
| 1599 | if (int.length > exponent) { |
| 1600 | // Place the decimal point at the int length count minus exponent |
| 1601 | result = this.insertAt(int, '.', int.length - exponent); |
| 1602 | } else { |
| 1603 | // If that decimal point is greater than the int length, pad with zeros (ie. Number('-123.4567e-6') --> -0.0001234567) |
| 1604 | result = `0.${'0'.repeat(exponent - int.length)}${int}`; |
| 1605 | } |
| 1606 | |
| 1607 | result = `${result}${float?float:''}`; |
| 1608 | } else { // Positive exponent |
| 1609 | if (float) { |
| 1610 | value = `${int}${float}`; // Remove the '.', if any |
| 1611 | if (exponent < float.length) { |
| 1612 | result = this.insertAt(value, '.', +exponent + int.length); |
| 1613 | } else { |
| 1614 | result = `${value}${'0'.repeat(exponent - float.length)}`; |
| 1615 | } |
| 1616 | } else { |
| 1617 | value = value.replace('.', ''); // Single case where val is '1.e4' |
| 1618 | result = `${value}${'0'.repeat(Number(exponent))}`; |
| 1619 | } |
| 1620 | } |
| 1621 | |
| 1622 | if (isNegative) { |
| 1623 | // Put back the negative sign, if any |
| 1624 | result = `-${result}`; |
| 1625 | } |