Is it possible to check if a given value is an infinite number using JavaScript?
Is it possible to check if a given value is an infinite number using JavaScript?
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");
}
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!')
}