Search code examples
javascripttype-conversionnaninfinity

Why parseInt(Infinity) returns NaN and parseFloat(Infinity) returns infinity?


What could be the reason to make these two functions behave differently for values infinity and -infinity. Does anyone ever find this inconsistency useful?

parseInt(Infinity); // NaN
parseFloat(Infinity); // Infinity

Solution

  • The answer to that question is right in the specs for the two functions:

    parseInt takes a string parameter.

    If the first character cannot be converted to a number, parseInt returns NaN.

    parseFloat

    parseFloat can also parse and return the value Infinity. You can use the isFinite function to determine if the result is a finite number (not Infinity, -Infinity, or NaN).

    parseInt can't return infinity because infinity is not within JavaScript's integer range. whereas it is a valid within the floating point range.

    As for useful? I can't say. In the domain that I work in, NaN means an error has happened and I don't believe I have ever used infinity