How do parseInt() and Number() behave differently when converting strings to numbers?
If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0
. Also multiply ("10" * 1
) or not not (~~"10"
). All of them are much faster of Number
and parseInt
.
They even have "feature" returning 0 for not number argument.
Here are Performance tests.
One minor difference is what they convert of undefined
or null
,
Number() Or Number(null) // returns 0
while
parseInt() Or parseInt(null) // returns NaN
parseInt()
:
NaN
will be returned.parseInt()
function encounters a non numerical value, it will cut off the rest of input string and only parse the part until the non numerical value.undefined
or 0, JS will assume the following:
ES5
specifies that 10 should be used then. However, this is not supported by all browsers, therefore always specify radix if your numbers can begin with a 0.Number()
:
Number()
constructor can convert any argument input into a number. If the Number()
constructor cannot convert the input into a number, NaN
will be returned.Number()
constructor can also handle hexadecimal number, they have to start with 0x
.console.log(parseInt('0xF', 16)); // 15
// z is no number, it will only evaluate 0xF, therefore 15 is logged
console.log(parseInt('0xFz123', 16));
// because the radix is 10, A is considered a letter not a number (like in Hexadecimal)
// Therefore, A will be cut off the string and 10 is logged
console.log(parseInt('10A', 10)); // 10
// first character isnot a number, therefore parseInt will return NaN
console.log(parseInt('a1213', 10));
console.log('\n');
// start with 0X, therefore Number will interpret it as a hexadecimal value
console.log(Number('0x11'));
// Cannot be converted to a number, NaN will be returned, notice that
// the number constructor will not cut off a non number part like parseInt does
console.log(Number('123A'));
// scientific notation is allowed
console.log(Number('152e-1')); // 15.21
parseInt()
-> Parses a number to specified redix.
Number()
-> Converts the specified value to its numeric equivalent or NaN if it fails to do so.
Hence for converting some non-numeric value to number we should always use Number() function.
eg.
Number("")//0
parseInt("")//NaN
Number("123")//123
parseInt("123")//123
Number("123ac") //NaN,as it is a non numeric string
parsInt("123ac") //123,it parse decimal number outof string
Number(true)//1
parseInt(true) //NaN
There are various corner case to parseInt()
functions as it does redix conversion, hence we should avoid using parseInt() function for coersion purposes.
Now, to check weather the provided value is Numeric or not,we should use nativeisNaN()
function