What is the difference between parseint() and Number()?

Asked

Viewed 1,535 times

10

What is the difference between the parseInt() and Number()?

If you use:

console.log(parseInt('100'));
console.log(parseInt('1'));
console.log(parseInt('a'));

console.log(Number('100'));
console.log(Number('1'));
console.log(Number('a'));

Both have the same result, what would be the difference and where these differences would be applied?

1 answer

13


They have different purposes, but can be used for common purposes.

The Number does type conversion, to Number. He will try to turn a string of digits into a number:

Number('0123'); // 123
Number('0123abc'); // NaN (aqui as letras estragam a conversão)

The parseInt is more versatile and complex. It tries to convert the first digits until a character that is not a digit appears:

parseInt('0123'); // 123
parseInt('0123abc'); // 123

So it parses (number and non-number analysis) and then converts the type. But there are some traps. The parseInt accepts two arguments as it allows to convert strings in numbers with decimal basis or not. Let’s take this example:

parseInt('0123abc'); // 123 - decimal
parseInt('0123abc', 8); // 83 - octal
parseInt('0123abc', 2); // 1 - binário

Thus it can be said that semantics is important and the type of string also. If we only have digits and want a decimal number the Number may be more appropriate, for example.

In cases of exponential notation, parseint will fail because it stops parsing when it finds letters on decimal basis. Example with 1000 in exponential format 1e3:

Number(1e3); // 1000 
Number('1e3'); // 1000 
parseInt('1e3'); // 1 (!errado!)
parseInt('1e3', 32); // 1475

The Number is also distinguished from parseInt in another aspect: the parseInt retort int(ie whole), while the Number returns numbers with or without decimal place, depending on the entry:

Number('10.5'); // 10.5
parseInt('10.5'); // 10
  • Great Sergio, I could also talk about the decimal numbers, but I’m leaving you the +1

  • @Guilhermenascimento obliged, I was completing and added exponential tb.

  • 3

    It is very good the answer will help many people ;)

  • I leave here a hint, it is also possible to convert to int using Operator + before the string. That is +"12"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.