-1

I need to find if my result is a number from 1 to 100, not infinite, but sometimes i have that result. How i can check if result in infinite.

I know i can do it using if statement

x =Math.floor(1/1)
if(x == 1/0){
return 0}
else{
return x}

But i need it on one line

x =Math.floor(1/1)(1/0 ? "0" : x);

I try that but i have a error... what i missing? I need that because i use it for loop statement and have around 500 numbers to sort and calculate... but without that check sometimes i have infinite result..

Anyone can help?

Piotr Mirosz
  • 846
  • 9
  • 20
  • 2
    Instead of adding a workaround you should fix the problem. And why _"But i need it on one line"_? – Andreas Feb 09 '19 at 14:06
  • 4
    Possible duplicate of [How do I check if a number evaluates to infinity?](https://stackoverflow.com/questions/4724555/how-do-i-check-if-a-number-evaluates-to-infinity) – adiga Feb 09 '19 at 14:08
  • If you have to use this in a lot of places, the solution isn't really "I need shorter code". Extract the logic into a function or even fix the problem so you don't have to do the check. – VLAZ Feb 09 '19 at 14:16
  • 1
    Maybe you should figure out why you have Infinity and fix that? – epascarello Feb 09 '19 at 14:19
  • because sometimes i have 0 input. I use ajax call to get object from API, after that i have to sort everything, main elements from object i working on are exam results for each topic, so if someone did not make test yet he will have 0 (there is 220 exams). Thats why sometimes i will have infinite output. Already have 7 loots each as nested. less code = less file weight, less file = faster output. – Piotr Mirosz Feb 10 '19 at 12:52

2 Answers2

2

Infinity

console.log((1/0)=== Infinity)
console.log((1/10)=== Infinity)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
2

You can use Number.isFinite:

let x = Math.floor(1/1);
console.log(Number.isFinite(x)? x :0);

console.log(1/0 === Infinity);
console.log(1/0 === -Infinity); //fails for -Infinity
console.log(-1/0 === -Infinity); //number has to be -ve for this to work

//Takes care of both -Infinity and Infinity
console.log(`Number.isFinite() for -Infinity ${Number.isFinite(-Infinity)}`);
console.log(`Number.isFinite() for Infinity ${Number.isFinite(Infinity)}`);

//Returns false for NaN, null and undefined
console.log(`Number.isFinite() for NaN ${Number.isFinite(NaN)}`);
console.log(`Number.isFinite() for null ${Number.isFinite(null)}`);
console.log(`Number.isFinite() for undefined ${Number.isFinite(undefined)}`);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44