DEV Community

Discussion on: You should stop using `parseInt()`

Collapse
 
andreidascalu profile image
Andrei Dascalu

Ok, but you did sum up the issue yourself in the examples. ParseInt will order to an integer whereas Number will get the proper numeric representation. Which means the outcome ma not be an int, which is what ParseInt guarantees .
The use of ParseInt can be replaced with Number if and only if it's accompanied by Math.round. This is not an edge case or an odd use case, it's the missing piece to have the intended outcome: an integer. The odd case is requiring the use of radix.

Collapse
 
darkmavis1980 profile image
Alessio Michelini

True, in fact if you want to take a string that could contain a float, and you want an integer, in that case you want to use that, but I'm not talking about that case, I'm talking about having the actual number correctly translated from a string to a number, which is probably the most common case.

Collapse
 
andreidascalu profile image
Andrei Dascalu

The most common case for ParseInt is to get the correct number from a string with the even expectation of getting a float .... from a function that has int in the name? I hardly believe that.
I have never seen in 20 years a case of parseInt used with the expectation of getting anything except an int.

Thread Thread
 
darkmavis1980 profile image
Alessio Michelini

Unfortunately I see it using it for what Number is supposed to do, many, many times.
Btw, if you just need to get the integer (that is a positive number) from a string containing a float, then you should use double tilde operator, which does the same as Math.floor, but just 10 times faster (in Node at least), for example:

console.log(~~'3.2'); // returns 3
console.log(parseInt('3.2')); // returns 3
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
markgoho profile image
Mark Goho

double tilde...🤯

Collapse
 
andreidascalu profile image
Andrei Dascalu

My point is mostly:

  • the performance comparison is moot because the functions discussed don't do the same thing
  • the correct way to formulate the use case for Number is: you should use Number when you want to extract the correct numeric value in full from a string AND you don't care about the resulting type.
  • use case for ParseInt: you want to ensure conversion to an integer OR the partial extraction of an integer (similar for float)