What's the difference between parseInt () and Number ()?

7

What is the difference between 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 would these differences be applied?

    
asked by anonymous 27.01.2017 / 00:01

1 answer

9

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

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

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

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

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

So it does parse (analysis of numbers and non-numbers) and then converts the type. But have some pitfalls. parseInt accepts two arguments, as it allows you to convert strings in decimal numbers or not . Let's look at this example:

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

So it can be said that the semantics are important and the type of string as well. If we only have digits and want a number in decimal basis the Number may be more appropriate, for example.

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

Number(1e3); // 1000 
Number('1e3'); // 1000 
parseInt('1e3'); // 1 (!errado!)
parseInt('1e3', 32); // 1475
The Number also differs from parseInt in another aspect: parseInt returns int (ie integers ), whereas Number returns numbers with or without decimal place, depending on the entry:

Number('10.5'); // 10.5
parseInt('10.5'); // 10
    
27.01.2017 / 00:15