How to determine if a number is infinite using JavaScript?

6

Is it possible to check if a given value is an infinite number using JavaScript?

    
asked by anonymous 06.09.2016 / 22:04

2 answers

4

As an example of the other response that was very good, you can also do this:

var n = ...; //Valor infinito ou não
var isInfinite = (!isNaN(n) && !isFinite(n));

console.log(isInfinite);

The isNaN is to prevent that !isFinite(n); return true may receive a number NaN

You could move to a function to make it easier:

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

Or

function isInfinite(num) {
     return num == Number.POSITIVE_INFINITY ||
            num == Number.NEGATIVE_INFINITY;
}

The usage would look like this:

alert(isInfinite(numero));

However, I read in the first edition that you used a number like this: 100000000000000000000000000000100000000000000000000000000000 , in fact this is not infinite, this would be a number that exceeds the limit

A simple test:

function checkNumberSizeValide(num) {
    return num <= Number.MAX_SAFE_INTEGER;
}

function isInfinite2(num) {
     return num == Number.POSITIVE_INFINITY ||
            num == Number.NEGATIVE_INFINITY;
}

var valor = window.prompt("Digite um numero, pode ser inteiro ou quebrado, exemplo 1.0000002");

if (/^(\d+|\d+[.]\d+)$/.test(valor)) {
    valor = Number(valor);

    console.log("valor", valor);

    console.log("O numero é valido dentro do limite máximo:", checkNumberSizeValide(valor));
} else {
    alert("Digite um numero");
}
    
07.09.2016 / 02:41
8

You can use the isFinite() function:

console.log(!isFinite(Number.MAX_SAFE_INTEGER)); // false
console.log(!isFinite(Infinity));                // true

Another way is to compare the value with and Number.POSITIVE_INFINITY :

if (numero == Number.POSITIVE_INFINITY || numero == Number.NEGATIVE_INFINITY) {
    alert('Número infinito!');
} else {
    alert('Número finito!')
}
    
06.09.2016 / 22:30