Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting -Infinity to Zero

Tags:

javascript

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?

like image 949
Learner Avatar asked Mar 02 '26 18:03

Learner


2 Answers

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);
like image 131
Riccardo Gai Avatar answered Mar 07 '26 09:03

Riccardo Gai


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.

like image 36
Mehrdad Avatar answered Mar 07 '26 10:03

Mehrdad