【JS】 Difference between parseInt() and Number()

I’ve only used parseInt() until now, but I had a chance to see pull-request using Number(), so I checked it, so I made a note of it.

Differences in behavior

Number() called as a function performs type conversion, parseInt() performs analysis.

parseInt('20p') // => 20
parseInt('10100', 2) // => 20 (Binary number)
parseInt('2e1') // => 2

Number('20p') // => NaN
Number('2e1') // => 20(=2 x 10^1)

Learn a little more about Number()

Number() does not detect implicit octal numbers, but it can detect explicit octal notation.

Number('010') // 10
Number('0o10') // 8 (explicit octal number)

parseInt('010') // 8 (implicit octal number)
parseInt('010', 10) // 10 (decimal radix used)

You can also process hex notation numbers, such as parseInt().

Number('0xF') // 15 (hex number)
parseInt('0xF') // 15 (hex number)

From a performance perspective

typeof parseInt('123') => number
typeof Number('123) => number
typeof new Number('123') => object

The first two return primitives instead of objects, which improves performance.

Summary

parseInt() converts a numeric portion of a string containing a number into a numeric value.

Number() interprets the meaning of a string that contains a number and converts it to a number. If the string does not match the grammar, it becomes NaN.

Reference

What is the difference between parseInt() and Number()?
How do parseInt() and Number() behave differently when converting strings to numbers?
タイトルとURLをコピーしました