DEV Community

yns
yns

Posted on

Difference Between Number() and parseInt() in Converting Strings?

Number(): Searches the entire string for numbers. If it finds anything else, it will return NaN (short for Not a Number).

parseInt() / parseFloat(): Returns the first number in the string, ignoring the rest. If there are no numbers at the beginning of the string, it will return NaN.

let's take an example:

Example 1:
let a = "1hola1";
console.log(Number(a));
console.log(parseInt(a));
output->
NaN
1

Example 2:
let a = "1";
console.log(Number(a));
console.log(parseInt(a));
output->
1
1

In conclusion , We use Number() for the Strings that only contains numbers,the parseInt() does the opposite.

Top comments (0)