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
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( function:
" 24" -> 24)NaN" 42answer" -> 42)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:
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:
+ or - -> number (integer)0NaNFor 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
ToNumber abstract operation in ECMAScript standard