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

JavascriptStringNumbersFormat

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

###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 - Javascript

Try something like this

Demo

Number("4.874915326E7").toPrecision()

Solution 3 - Javascript

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 4 - Javascript

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

+"4.874915326E7" // == 48749153.26

Solution 5 - Javascript

Preamble

While other answers are sufficient and correct, to be able to correctly parse numbers from strings, it is useful to understand how type coercion (conversion in your case) works at least at high level.

Coercion rules

There are rules that define how conversion is performed when you invoke utilities like parseInt, parseFloat, Number constructor or + unary operator:

parseInt(<value>, [radix]) function:

  • ignores leading whitespaces (" 24" -> 24)
  • empty strings return NaN
  • first non-numeric char finishes parsing (" 42answer" -> 42)
  • under above rule, decimal places finish parsing as well

The third rule is exactly why exponent part (ExponentPart consists of ExponentIndicator and SignedInteger as defined in standard) is ignored - as soon as the e char is encountered, parsing stops and the function returns the number parsed so far. In fact, it stops earlier - when the decimal point is first encountered (see the last rule).

parseFloat() is identical to parseInt, except:

  • it parses first decimal point
  • ignores leading 0 (thus hexadecimal can't be parsed)

As a rule of thumb, you should use parseInt when converting to an "integer" and parseFloat to "float" (note that they are actually the same type).

Number() constructor and unary +:

  • For boolean -> true to 1, false to 0

  • For null -> 0 (because null is falsy)

  • For undefined -> NaN

  • For numbers: pass-through

  • For strings:

    • only numeric [0-9] chars, starts with numeric or + or - -> number (integer)
    • same, but contains floating-point -> number (floating-point)
    • contains hexadecimal -> number (integer)
    • empty string -> 0
    • all other cases -> NaN
  • For objects, their valueOf() method is called. If result is NaN, then toString() method is called. Under the hood, the object is converted to primitive and that primitive is converted to number.

  • For symbols and BigInts -> TypeError is thrown

Note on number format

As the question still attracts answers and comments that are concerned with formatting (as validly stated by the accepted answer), it should be stated that:

> As applied to programming, there is a strict meaning of "number format":
> representation of the numeric value > > "conversion" also has a strict meaning as type conversion (see standard)

ECMAScript implements double-precision 64-bit format and that's the only "format" it has. The question asks about converting a String to number format, therefore answers are expected to provide info on:

> How to convert String to Number given the value represents a number in e-notation

References

  1. ToNumber abstract operation in ECMAScript standard
  2. One of the best reads I had on this topic and many others: Matt Frisbie's "Professional Javascript for Web Developers".
  3. Type coercion explained (blog post)

Solution 6 - Javascript

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'});
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOlgaView Question on Stackoverflow
Solution 1 - JavascriptJoseph MarikleView Answer on Stackoverflow
Solution 2 - JavascriptPranay RanaView Answer on Stackoverflow
Solution 3 - JavascriptMatt RiedemannView Answer on Stackoverflow
Solution 4 - JavascriptYaroslav MelnichukView Answer on Stackoverflow
Solution 5 - JavascriptOleg Valter is with UkraineView Answer on Stackoverflow
Solution 6 - JavascriptotterslideView Answer on Stackoverflow