Search code examples
javascriptnumbers

Why does javascript think my string is a number?


!isNaN("0x8d0adfd44b4351e5651c09566403e7edc586243dc0890f8e86c043a924a9592c")

The above results in TRUE, meaning javascript thinks this is a number.

I've also tried

!isNaN(parseFloat("0x8d0adfd44b4351e5651c09566403e7edc586243dc0890f8e86c043a924a9592c"))

which also returns TRUE.


Solution

  • The value of

     Number("0x8d0adfd44b4351e5651c09566403e7edc586243dc0890f8e86c043a924a9592c")
    

    is

    6.379532493375848e+76
    

    which means the value of the hexadecimal string, when coerced to a number, is within the range of floating point numbers in JavaScript and is certainly not NaN, but has suffered a large reduction in precision.

    However parseFloat("0x8d0adfd44b4351e5651c09566403e7edc586243dc0890f8e86c043a924a9592c")

    returns 0 (zero). The explanation of this is that parseFloat does not support non decimal string literals - which means strings in hexadecimal notation are excluded (amongst others), and only that part of the argument that precedes non digit characters is parsed. The 0 immediately before the x in 0x... is a decimal digit and hence is parsed and returned by parseFloat.

    FYI, you may wish to look into the difference between the global isNaN function and the Number.isNaN method - they are not exactly the same:

    • the global isNaN function function will coerce its argument to a string if necessary
    • The Number.isNaN method does not cooerce its argument before testing if it is NaN and will return false for all argument types that are not numbers, in particular for arguments of type string.