114

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?

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Homer_J
  • 3,277
  • 12
  • 45
  • 65

8 Answers8

204
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))
{
    // ...
}
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • 4
    Why use `Number.(POSITIVE|NEGATIVE)_INFINITY` instead of `-?Infinity` or `-?1/0`? – Eli Grey Jan 18 '11 at 13:37
  • 5
    @Eli: The global `Infinity` property isn't read-only which means that it can be redefined: For example, `var x = 42; Infinity = 42; alert(x === Infinity);` displays *"true"*. (Admittedly that's an obscure case, and anyone who decides to redefine `Infinity`, `NaN` etc should expect odd things to happen.) – LukeH Jan 18 '11 at 13:49
  • 2
    Ignoring the fact that `Number.(POSITIVE|NEGATIVE)_INFINITY` isn't read-only either, `Infinity` *is* read-only in strict mode. Also, what about the `-?1/0` case I presented to you? Anyways, you should almost always use `isFinite` instead. – Eli Grey Jan 18 '11 at 15:36
  • 1
    @Eli: In my tests `Number.POSITIVE_INFINITY` and `Number.NEGATIVE_INFINITY` *are* read-only (tested on Chrome8, FF3.6 and IE8). Using `1/0` works fine but it won't be so obvious to maintainers of your code what you're actually trying to test for. I agree that using `isFinite` is almost always the better way to do things -- that's why I mentioned it in my answer -- but only the OP can decide whether it meets their requirements. – LukeH Jan 18 '11 at 15:58
  • 5
    They're not read-only (read: *non-configurable*), they're just accessors with getters but no setters. You can redefine them with `Object.defineProperty` and `__defineGetter__`. `Infinity`, on the other hand, *is* non-configurable in strict mode. – Eli Grey Jan 19 '11 at 20:12
  • Is this the only case where it's worth to use == instead of ===? What happens behind the scene when I use === to compare max double against Number.POSITIVE_INFINITY? (it returns false, of course). – Alexander Mar 15 '16 at 18:17
  • I would suggest to use javascript triple equals when checking for Infinity. Ex result === Number.POSITIVE_INFINITY || result === Number.NEGATIVE_INFINITY Instead of result == Number.POSITIVE_INFINITY || result == Number.NEGATIVE_INFINITY – Armen Zakaryan Apr 06 '20 at 10:35
17

In ES6, The Number.isFinite() method determines whether the passed value is a finite number.

Number.isFinite(Infinity);  // false
Number.isFinite(NaN);       // false
Number.isFinite(-Infinity); // false

Number.isFinite(0);         // true
Number.isFinite(2e64);      // true
zangw
  • 43,869
  • 19
  • 177
  • 214
10

A simple n === n+1 or n === n/0 works:

function isInfinite(n) {
  return n === n/0;
}

Be aware that the native isFinite() coerces inputs to numbers. isFinite([]) and isFinite(null) are both true for example.

ryanve
  • 50,076
  • 30
  • 102
  • 137
  • 1
    This answer is plain wrong. `n === n+1` evaluates to true for all numbers larger than 2^53, i.e., 1e30. The division hack works, even for NaN and -Infinity. However, LukeH's answer gives you waaaay more readable code. – tglas Sep 04 '18 at 06:47
  • @tglas Why is the plus like that? Glad the division is solid. IMO my code is more readable and more inclusive because math is more universal than words. – ryanve Sep 12 '18 at 14:40
  • 1
    Because IEEE 64bit floats have 53 significant binary digits (see https://en.wikipedia.org/wiki/IEEE_754 ), so `n+1` cannot be represented and is subject to rounding. Well, even integers are affected by rounding errors. Btw, I don't think that your code is "math-proof", just try `n === n/-0`. When completing the reals with +/-inf, your limit is not well-defined unless the underlying zero sequence is assumed to be positive. – tglas Sep 13 '18 at 21:14
  • Thanks @tglas I'll always love that JavaScript can divide by zero :) – ryanve Sep 18 '18 at 20:45
4

Perform the plain ol’ comparison:

(number === Infinity || number === -Infinity)

or to save several characters:

Math.abs(number) === Infinity

Why to use this

  1. !(Number.isFinite(number)) breaks on NaN inputs.
  2. Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY can be redefined; they are configurable.
  3. Infinity and -Infinity are read-only in the strict mode.
  4. It is the shortest solution.
2

Actually n === n + 1 will work for numbers bigger than 51 bit, e.g.

1e16 + 1 === 1e16; // true
1e16 === Infinity; // false
Yuri
  • 149
  • 1
  • 5
0

I like to use Lodash for a variety of defensive coding reasons as well as readability. ES6 Number.isFinite is great and does not have issues with non-numeric values, but if ES6 isn't possible, you already have lodash, or want briefer code: _.isFinite

_.isFinite(Infinity); // false
_.isFinite(NaN); // false
_.isFinite(-Infinity); // false

_.isFinite(null); // false
_.isFinite(3); // true
_.isFinite('3'); // true
random_user_name
  • 25,694
  • 7
  • 76
  • 115
-1

I've ran into a scenario that required me to check if the value is of the NaN or Infinity type but pass strings as valid results. Because many text strings will produce false-positive NaN, I've made a simple solution to circumvent that:

  const testInput = input => input + "" === "NaN" || input + "" === "Infinity";

The above code converts values to strings and checks whether they are strictly equal to NaN or Infinity (you'll need to add another case for negative infinity).

So:

testInput(1/0); // true
testInput(parseInt("String")); // true
testInput("String"); // false
dmitrizzle
  • 774
  • 6
  • 15
  • This post does not really deal with the actual question here and would've been better as a comment under the accepted answer. The OP is about numbers and infinity, not strings and `NaN`s, etc. – code_dredd Sep 30 '19 at 21:41
  • You're probably right, @code_dredd - the anecdote isn't relevant. But the solution still works: it can detect the infinity number - please correct me if I'm wrong. – dmitrizzle Oct 01 '19 at 23:32
  • That's beside the point. There's already an answer that shows how to do this _correctly_. What you have "works" simply because the language itself does silly things and is inconsistent with how it manages types. Please save yourself from writing hack code like this. – code_dredd Oct 01 '19 at 23:38
  • Would it make you happier if I used `toString()` instead? Feel free to downvote or state reasons how this could yield inconsistent results or why exactly this method isn't recommended. So far, I still feel it adds an option for whoever's looking for an answer and there aren't any concrete reasons why this is dangerous, unstable, etc. – dmitrizzle Oct 03 '19 at 22:08
-2

You can use isFinite in window, isFinite(123):

You can write a function like:

function isInfinite(num) {
 return !isFinite(num);
}

And use like:

isInfinite(null); //false
isInfinite(1); //false
isInfinite(0); //false
isInfinite(0.00); //false
isInfinite(NaN); //true
isInfinite(-1.797693134862316E+308); //true
isInfinite(Infinity); //true
isInfinite(-Infinity); //true
isInfinite(+Infinity); //true
isInfinite(undefined); //true

You can also Number.isFinite which also check if the value is Number too and is more accurate for checking undefined and null etc...

Or you can polyfill it like this:

Number.isFinite = Number.isFinite || function(value) {
  return typeof value === 'number' && isFinite(value);
}
Alireza
  • 100,211
  • 27
  • 269
  • 172