Differencebetween Parseint() and Number()

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 just parseInt)

    • 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 just parseFloat)

    • Similar to parseInt, except that it allows for a decimal part to be interpreted
    • Only parses to base-10
  • 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
  • the + operator

    • Basically the same as Number(), but in operator form.
  • 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.

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.

What is the difference between int parseInt(String s) and Integer.valueOf(String s)? Also What is radix with a numerical parameter {10 or etc}

The two methods are almost the same in terms of logic.

The difference is that valueOf returns an Integer and parseInt returns an int.

You can see that both call parseInt(s, 10), which means they treat the input String as a number of radix (base) 10 (i.e. a decimal number).

public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}

public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}

parseInt vs unary plus, when to use which?

Well, here are a few differences I know of:

  • An empty string "" evaluates to a 0, while parseInt evaluates it to NaN. IMO, a blank string should be a NaN.

      +'' === 0;              //true
    isNaN(parseInt('',10)); //true
  • The unary + acts more like parseFloat 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; //true
  • parseInt and parseFloat 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, and NaN if none was parsed as a number.

    The unary + on the other hand will return NaN if the entire string is non-convertible to a number.

      parseInt('2a',10) === 2; //true
    parseFloat('2a') === 2; //true
    isNaN(+'2a'); //true
  • As seen in the comment of @Alex K., parseInt and parseFloat will parse by character. This means hex and exponent notations will fail since the x and e 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.


Related Topics



Leave a reply



Submit