Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert numbers like 1e+10, 5e-6 and so on to the form 10^10, 5 * 10^-6?

I have a calculator that outputs values ​​and converts them to an exponent using the toExponential() function.
But now I want these numbers to take on a more "human-readable" form.
I tried to do it with array iteration but I doubt my solution is correct

In the array, I get several dozen elements that look like [‘1’, ‘+6’], [‘5’, ‘-12’]. I separated them by the character "e"

The result is displayed in the table as a string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Right now I managed to change all units to 10
But I still need to know the math operator and other numbers other than one

convertToHumanReadableNumber(num) {
      let arr = []
      arr.push(num.split('e'))
      let arr2 = arr.map(el => {
        if (el[0] == '1') {
          return el[0] = '10'   
         }
      })
    }

>Solution :

You can use JavaScript’s built-in toExponential() method to convert a number to the exponential notation:

let num1 = 1e+10;
let result1 = num1.toExponential();
console.log(result1); // logs "1e+10"

let num2 = 5e-6;
let result2 = num2.toExponential();
console.log(result2); // logs "5e-6"

To convert the exponential notation to the desired format, you can extract the exponent part and the mantissa part of the number and then format it as desired:

let num1 = 1e+10;
let [mantissa, exponent] = num1.toExponential().split('e');
let result1 = `${mantissa} * 10^${exponent}`;
console.log(result1); // logs "1 * 10^10"

let num2 = 5e-6;
let [mantissa, exponent] = num2.toExponential().split('e');
let result2 = `${mantissa} * 10^${exponent}`;
console.log(result2); // logs "5 * 10^-6"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading