Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between parseInt() and Number()?

How do parseInt() and Number() behave differently when converting strings to numbers?

like image 454
Mark Avatar asked Nov 03 '10 18:11

Mark


People also ask

What is the difference between number () and parseInt?

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.

Is it better to use number or parseInt?

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.

What does number parseInt () do?

The Number. parseInt() method parses a string argument and returns an integer of the specified radix or base.

What is the difference between integer parseInt and int?

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.


2 Answers

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 
like image 187
Christian C. Salvadó Avatar answered Sep 22 '22 21:09

Christian C. Salvadó


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.

like image 27
letronje Avatar answered Sep 22 '22 21:09

letronje