Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

1 Answers

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

like image 69
Jeremy J Starcher Avatar answered Oct 27 '25 14:10

Jeremy J Starcher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!