What is the difference between parseInt(string) and Number(string) in JavaScript?
parseInt("123qwe")
returns 123
Number("123qwe")
returns NaN
In other words parseInt()
parses up to the first non-digit and returns whatever it had parsed. Number()
wants to convert the entire string into a number, which can also be a float BTW.
EDIT #1: Lucero commented about the radix that can be used along with parseInt()
. As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).
EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number()
in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat()
aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui")
also returns NaN
). And the biggest difference is the use of radix that Number()
doesn't know of and parseInt()
may indirectly guess from the given string (that can cause weird results sometimes).
What is the difference between parseInt() and Number()?
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
What is the critical difference between 'Number.parseInt()', 'Number.parseFloat()', 'Number()' or '+'?
Number.parseInt
method (or justparseInt
)- Ignores leading and trailing whitespace
- Parses a leading number to an integer (not a floating point number)
- Ignores invalid trailing data
- Lets you set the base to use when interpreting the number
- Will interpret text starting with
0x
as hexadecimal, if another base was not provided - Returns
NaN
if the value could not be successfully parsed to an integer
Number.parseFloat
method (or justparseFloat
)- Similar to
parseInt
, except that it allows for a decimal part to be interpreted - Only parses to base-10
- Similar to
Number()
function (or class?)- Similar to
parseFloat
, but does not allow trailing text - Will return
0
for an empty string or a string that only contains whitespace - It's not a class; when called without
new
, it returns a primitive number
- Similar to
the
+
operator- Basically the same as
Number()
, but in operator form.
- Basically the same as
eval()
- Interprets and executes the given input as a JavaScript program.
- Given the string
"2"
, it will be interpreted as a numeric literal, and return that value since it's the result of the last expression in the program - Throws an error if the input was not a valid program.
JSON.parse()
- Parses the textual data as JSON-serialized data.
- If the data is valid, it creates the JavaScript objects/primitives that are represented by the data, and returns them.
- If the data is invalid, it throws an error.
- Given the string
"2"
, it will be interpreted as a numeric literal, and return the value that was successfully parsed out of it according to the parsing requirements of JSON.
So you decide which is appropriate to use based on their capabilities.
What is the difference between Number(...) and parseFloat(...)
No. Both will result in the internal ToNumber(string)
function being called.
From ES5 section 15.7.1 (The Number Constructor Called as a Function):
When
Number
is called as a function rather than as a constructor, it performs a type conversion...Returns a Number value (not a Number object) computed by
ToNumber(value)
if value was supplied, else returns+0
.
From ES5 section 15.1.2.3 (parseFloat (string)):
...
If neithertrimmedString
nor any prefix oftrimmedString
satisfies the syntax of aStrDecimalLiteral
(see 9.3.1)
...
And 9.3.1 is the section titled "ToNumber Applied to the String Type", which is what the first quote is referring to when it says ToNumber(value)
.
Update (see comments)
By calling the Number
constructor with the new
operator, you will get an instance of the Number
object, rather than a numeric literal. For example:
typeof new Number(10); //object
typeof Number(10); //number
This is defined in section 15.7.2 (The Number Constructor):
When
Number
is called as part of anew
expression it is a constructor: it initialises the newly created object.
What is the difference between parseInt(string) and Number(string) in JavaScript?
parseInt("123qwe")
returns 123
Number("123qwe")
returns NaN
In other words parseInt()
parses up to the first non-digit and returns whatever it had parsed. Number()
wants to convert the entire string into a number, which can also be a float BTW.
EDIT #1: Lucero commented about the radix that can be used along with parseInt()
. As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).
EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number()
in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat()
aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui")
also returns NaN
). And the biggest difference is the use of radix that Number()
doesn't know of and parseInt()
may indirectly guess from the given string (that can cause weird results sometimes).
parseInt vs unary plus, when to use which?
Well, here are a few differences I know of:
An empty string
""
evaluates to a0
, whileparseInt
evaluates it toNaN
. IMO, a blank string should be aNaN
.+'' === 0; //true
isNaN(parseInt('',10)); //trueThe unary
+
acts more likeparseFloat
since it also accepts decimals.parseInt
on the other hand stops parsing when it sees a non-numerical character, like the period that is intended to be a decimal point.
.+'2.3' === 2.3; //true
parseInt('2.3',10) === 2; //trueparseInt
andparseFloat
parses and builds the string left to right. If they see an invalid character, it returns what has been parsed (if any) as a number, andNaN
if none was parsed as a number.The unary
+
on the other hand will returnNaN
if the entire string is non-convertible to a number.parseInt('2a',10) === 2; //true
parseFloat('2a') === 2; //true
isNaN(+'2a'); //trueAs seen in the comment of @Alex K.,
parseInt
andparseFloat
will parse by character. This means hex and exponent notations will fail since thex
ande
are treated as non-numerical components (at least on base10).The unary
+
will convert them properly though.parseInt('2e3',10) === 2; //true. This is supposed to be 2000
+'2e3' === 2000; //true. This one's correct.
parseInt("0xf", 10) === 0; //true. This is supposed to be 15
+'0xf' === 15; //true. This one's correct.
Difference in efficacy between parseInt() and Number.isInteger() in following Javascript array scenario?
I do not see why we would need to parse integers if they are already integers.
You don't need to. This is abuse of parseInt
. They should have used Math.floor
instead for their intented purpose.
Why
parseInt()
does not throw an error since its parameter asks for a string?
Because it's an old API, and it's very lenient. Instead of throwing errors, it simply coerces its argument to a string, then tries to parse that.
My primary question: Are both equally acceptable?
No, parseInt
is absolutely inacceptable. You found a much better solution with isInteger
. The reason why they didn't use it probably is that isInteger
is a relatively new function, added with ES6.
Related Topics
How to Redefine a JavaScript Class's Method
How to Check If the React Component Is Unmounted
How to Flatten Nested Array in JavaScript
Extending Built-In Natives in Es6 with Babel
Access-Control-Allow-Origin Denied Spotify API
Angularjs Multiple Filter with Custom Filter Function
How to Filter Array When Object Key Value Is in Array
Componentdidmount Equivalent on a React Function/Hooks Component
How to Iterate (Keys, Values) in JavaScript
Jquery.Getjson - Access-Control-Allow-Origin Issue
How to Access a Child's State in React
App.Settings - the Angular Way
Is It Safe to Assume Strict Comparison in a JavaScript Switch Statement
Facebook How to Check If User Has Liked Page and Show Content
Jquery - Script Tags in the HTML Are Parsed Out by Jquery and Not Executed
What Does $.When.Apply($, Somearray) Do