-5

How would i check if a decimal is negative? Because the if statement automatically turns it into a number...

Example:

var x = -0.24324; 

how would i parse it so it tells me x is negative/positive?

Thanks

Edit: Maybe i phrased it badly, the variable changes so something it will be positive like 0.00000001, sometimes -0.0003423423, sometimes 0.0000000234

If i put it in a if statement everything is automatically turned into 0 right? And i can't use a parseFloat in the if statement?

Pradnya Sinalkar
  • 1,116
  • 4
  • 12
  • 26
Benyaman
  • 451
  • 2
  • 10
  • 25

3 Answers3

0

Just check if x less than zero since it's a number:

if (x < 0) {
  // it's negative
}
ide
  • 19,942
  • 5
  • 64
  • 106
0
  1. You can use isNaN() function to check whether it is valid number or not.
  2. If it is, then you can check for positive or negative value.

Something like this:

var x = "-123"
var y = -456;
var z = '-123a';

if(!isNaN(x) && x < 0) {
  console.log(x + ' is negative');
}

if(!isNaN(y) && y < 0) {
  console.log(y + ' is negative');
}

if(!isNaN(z) && z < 0) {
  console.log(z + ' is negative');
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0
const num = -8;

// Old Way

num === 0 ? num : (num > 0 ? 1 : -1); // -1

// ✅ ES6 Way

Math.sign(num); // -1
c-2k
  • 1
  • 1