How do I check if a number evaluates to infinity?

Homer_J picture Homer_J · Jan 18, 2011 · Viewed 58.7k times · Source

I have a series of Javascript calculations that (only under IE) show Infinity depending on user choices.

How does one stop the word Infinity appearing and for example, show 0.0 instead?

Answer

LukeH picture LukeH · Jan 18, 2011
if (result == Number.POSITIVE_INFINITY || result == Number.NEGATIVE_INFINITY)
{
    // ...
}

You could possibly use the isFinite function instead, depending on how you want to treat NaN. isFinite returns false if your number is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN.

if (isFinite(result))
{
    // ...
}