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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With