Learner
Learner

Reputation: 55

Converting -Infinity to Zero

I am working on some calculation and my calculation result is giving me NaN. So I used something like below which converts it 0 which was fine

Number((((0-0)/0)*100).toFixed(2)) || 0

until the result is -Infinity and i found out that -Infinity is numeric value. So now i did something like below to convert -Infinity to 0

var result = Number((((0-18)/0)*100).toFixed(2)) || 0
if (result == Number.POSITIVE_INFINITY || result == Number.NEGATIVE_INFINITY)
{
    result=0;
	console.log(result)
}

This is solving the problem but is there a shorter or better approach?

Upvotes: 2

Views: 1873

Answers (4)

Nithin Thampi
Nithin Thampi

Reputation: 3679

I second the answer from @Riccardo Gai. Another approach could be to make use of the below 2 points in Javscript.

**Any number % Infinity  ===  number** 

**(Infinity || -Infinity) % Infinity ===  NaN**

So you can basically rewrite your code as...

Number((((0-18)/0)*100).toFixed(2)) % Infinity || 0

You can try out the below snippets..

console.log(Number((((0-0)/3)*100).toFixed(2)) % Infinity || 0);
console.log(Number((((0-1)/0)*100).toFixed(2)) % Infinity || 0);
console.log(Number((((1-0)/0)*100).toFixed(2)) % Infinity || 0);
console.log(Number((((1-2)/0)*100).toFixed(2)) % Infinity || 0);
console.log(Number((((1-2)/2)*100).toFixed(2)) % Infinity || 0);
console.log(Number((((0-18)/0)*100).toFixed(2)) % Infinity || 0);

Upvotes: 1

axiac
axiac

Reputation: 72216

This is solving the problem but is there a shorter or better approach?

The correct approach is to never divide by zero.

var a = 1;
var b = 2;
var c = 3;

var result;
if (c != 0) {
  result = ((a-b)*100)/c;
} else {
  // Zero is neither the correct result nor a good replacement for it
  // The correct approach here is to throw an exception
  result = 0;
}

Upvotes: 1

Mehrdad
Mehrdad

Reputation: 583

The fastest way would be using bitwise Not operator:

var result = ~~Number((((0-18)/0)*100).toFixed(2))

Which executes a lot faster than other methods and is shorter to write.

Upvotes: 2

Riccardo Gai
Riccardo Gai

Reputation: 421

In Javascript exists isFinite() that returns if a number is finite or not. So:

var result = isFinite(Number((((0-18)/0)*100).toFixed(2))) || 0;
console.log(result);

Upvotes: 4

Related Questions