Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a number evaluates to infinity?

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?

like image 367
Homer_J Avatar asked Jan 18 '11 13:01

Homer_J


People also ask

How do you know if a value is infinity?

Try it. function div(x) { if (isFinite(1000 / x)) { return 'Number is NOT Infinity. '; } return 'Number is Infinity!

Which method is used to check if a number is infinite or not?

The math. isinf() method checks whether a number is infinite or not. This method returns True if the specified number is a positive or negative infinity, otherwise it returns False.

How do you check for infinity in typescript?

The Infinity is a global property i.e. it is a variable in a global scope. The Infinity can be either POSITIVE_INFINITY & NEGATIVE_INFINITY . We can check whether the number is finite by using the isFinite method.

How do you check if a parameter is a number?

In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.


2 Answers

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)) {     // ... } 
like image 118
LukeH Avatar answered Oct 18 '22 10:10

LukeH


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 
like image 32
zangw Avatar answered Oct 18 '22 10:10

zangw