How do I check if a number evaluates to infinity?

前端 未结 7 768
孤城傲影
孤城傲影 2020-12-07 19:24

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 a

相关标签:
7条回答
  • 2020-12-07 20:05

    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);
    }
    
    0 讨论(0)
  • 2020-12-07 20:06

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

    1e16 + 1 === 1e16; // true
    1e16 === Infinity; // false
    
    0 讨论(0)
  • 2020-12-07 20:09
    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))
    {
        // ...
    }
    
    0 讨论(0)
  • 2020-12-07 20:13

    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.

    0 讨论(0)
  • 2020-12-07 20:19

    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
    
    0 讨论(0)
  • 2020-12-07 20:22

    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
    
    0 讨论(0)
提交回复
热议问题