How do parseInt()
and Number()
behave differently when converting strings to numbers?
Differences. Number() converts the type whereas parseInt parses the value of input. As you see, parseInt will parse up to the first non-digit character. On the other hand, Number will try to convert the entire string.
Hence for converting some non-numeric value to number we should always use Number() function. eg. There are various corner case to parseInt() functions as it does redix conversion, hence we should avoid using parseInt() function for coersion purposes.
The Number. parseInt() method parses a string argument and returns an integer of the specified radix or base.
In case of Integer we can assign string to an object of Integer type using the Integer(String) constructor or by even use parseInt(String) to convert a String literal to an int value. Direct Conversion to Other base. In case of int we can't convert its integer value to other base.
Well, they are semantically different, the Number
constructor called as a function performs type conversion and parseInt
performs parsing, e.g.:
// parsing: parseInt("20px"); // 20 parseInt("10100", 2); // 20 parseInt("2e1"); // 2 // type conversion Number("20px"); // NaN Number("2e1"); // 20, exponential notation
Also parseInt
will ignore trailing characters that don't correspond with any digit of the currently used base.
The Number
constructor doesn't detect implicit octals, but can detect the explicit octal notation:
Number("010"); // 10 Number("0o10") // 8, explicit octal parseInt("010"); // 8, implicit octal parseInt("010", 10); // 10, decimal radix used
And it can handle numbers in hexadecimal notation, just like parseInt
:
Number("0xF"); // 15 parseInt("0xF"); //15
In addition, a widely used construct to perform Numeric type conversion, is the Unary +
Operator (p. 72), it is equivalent to using the Number
constructor as a function:
+"2e1"; // 20 +"0xF"; // 15 +"010"; // 10
typeof parseInt("123") => number typeof Number("123") => number typeof new Number("123") => object (Number primitive wrapper object)
first two will give you better performance as it returns a primitive instead of an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With