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 (8)

Collapse
 
sunny64 profile image
Sunny

You can use parseInt() on decimal values and it will return the floor of that number.
for eg:

parseInt(4.5)
output: 4

Number(4.5)
output: 4.5
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yns666 profile image
yns

For Sure ! You can also use the Math functions such as ( Math.floor() , Math.ceil() , etc...) to achieve that .

Collapse
 
sachin_kotian_b225f65d77f profile image
sachin kotian

why cant they just return 0? unpredictable

Collapse
 
endrits079 profile image
Endrit Shabani

because how would you know if it returned 0 because it got "0" or because it had an invalid string?

Collapse
 
hassantahir profile image
Hassan Tahir

welcome to javascript? :p

Collapse
 
sachin_kotian_b225f65d77f profile image
sachin kotian

been years now out of this shit moving to java

Collapse
 
mackson_isani_5914cc790e7 profile image
Mackson Isani

Number() for the win then!

Collapse
 
chuks_gabriel profile image
Chuks Gabriel

What if you pre-pend + to the variable? For example:

let a = +"1hola1";

What is executed under the hood for the type casting?`

parseInt() / parseFloat()
Or
Number()