Home > Net >  Why parseInt 0.11 is not NaN but 0?
Why parseInt 0.11 is not NaN but 0?

Time:12-21

Is this normal?

newItemRowNumber
'0.11'
parseInt(newItemRowNumber)
0

I would expect that it is not parseable.

CodePudding user response:

parseInt parses the string for real numbers 0-9 at the start of the string. When it encounters a non integer character it stops parsing, in this case the .

19aaa becomes 19
0.11 becomes 0
11.111 becomes 11
abc11 becomes NaN
0xDEAD becomes 57005(Because of hexadecimal numbers)

CodePudding user response:

From MDN:

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.

0 is a numerial.

. is not.

So it takes the 0, ignores the ., ignores everything after the ., and you get 0.

CodePudding user response:

This is normal because parseInt will just cut the fraction part from the given number string. And return the int value of the left side number of the dot. As you are parsing float its better you can use parseFloat()

console.log(parseFloat("0.11"))
>>0.11

CodePudding user response:

It is parsable because it look first char and it is a number so the value is 0 ,if you write character other than number than it's value will be NaN

  • Related