How to convert a String containing Scientific Notation to correct Javascript number format

68,672

Solution 1

Edit:

This answer seems to be generating some confusion. The original question was asking how to convert scientific notation in the form of a string to a number (so that it could be used for calculation). However, a significant number of people finding this answer seem to think it's about converting a number that is being represented by javascript as scientific notation to a more presentable format. If that is in fact your goal (presentation), then you should be converting the number to a string instead. Note that this means you will not be able to use it in calculations as easily.

Original Answer:

Pass it as a string to the Number function.

Number("4.874915326E7") // returns 48749153.26
Number("4E27") // returns 4e+27

Converting a Number in Scientific Notation to a String:

This is best answered by another question, but from that question I personally like the solution that uses .toLocaleString(). Note that that particular solution doesn't work for negative numbers. For your convenience, here is an example:

(4e+27).toLocaleString('fullwide', {useGrouping:false}) // returns "4000000000000000000000000000"

Solution 2

Try something like this

Demo

Number("4.874915326E7").toPrecision()

Solution 3

You can also use + sign in front of your string to get a number.

+"4.874915326E7" // == 48749153.26

Solution 4

I had a value like this 3.53048874968162e-09 and using Number.toFixed(20) worked for me:

value = new Number('3.53048874968162e-09')
//[Number: 3.53048874968162e-9]
value.toFixed(20)
//'0.00000000353048874968'

Solution 5

Using MathJs library worked best for me, tried a lot of these answers and none of them worked properly under certain circumstances. This worked perfectly. More at https://mathjs.org/

Solution, add MathJS and then call it like this:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/browser/math.js"  crossorigin="anonymous"></script>
    
    function toPlainString(num) {
        return math.format(num,  {notation: 'fixed'});
    }
Share:
68,672
Olga
Author by

Olga

Updated on November 18, 2020

Comments

  • Olga
    Olga over 3 years

    I have a String e.g: "4.874915326E7". What is the best way to convert it to a javascript number format? (int or float)? if I try parseInt(), the E at the end is ignored.