Skip to content Skip to sidebar Skip to footer

Why Does Javascript Parseint('0x4a') Return The Same As Parseint('0x4avv')?

Why does Javascript parseInt('0x4Avv') return the same as parseInt('0x4A') I was counting on parseInt('0x4Avv') to return NaN. Is there anyway to make it behave as such? Even wei

Solution 1:

Here is an excerpt from the MDN parseInt documentation

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

There isn't a built in way to make it behave otherwise, but you could conceivably write your own int parsing function using regex that could be more strict.

Solution 2:

The parseInt() function doesn't care about trailing garbage in the source string. The parseFloat() function shares that behavior.

If you want to convert a string to a number and do so in such a way as to ensure the string was "all number", you can use the + unary operator:

var num = +someString;

That gives you a JavaScript number, so if you want an integer you can instead use one of these:

var intval = ~~someString;
var intval = someString|0;

Feeding bad strings as in your examples to any of those techniques will leave you with NaN.

Solution 3:

parseInt ignores everything after an invalid number.

Here's is a little example of it behavior.

parseInt("12ab") // radix asumed to 10 since there isn't specified.// 1 -> valid number// 2 -> valid number// a -> not valid number, DROP everything after this including this..//// so it endup behaving like:parseInt("12") // 12

Solution 4:

As noted in previous answers, both parseInt and parseFloat will convert all inputs to a string and then attempt to parse all numerical values up to the first non-numerical value (see MDN documentation for further reading). However, if you are trying to cast a string to a number and desire that it return a NaN value if the entire string does not represent a number you can use the Number global object to do so:

> Number('0x4Avv')
NaN
> Number('0x4A')
74
> Number('0x4Av--9-0-90v')
NaN

Post a Comment for "Why Does Javascript Parseint('0x4a') Return The Same As Parseint('0x4avv')?"