I want to check if a number is negative. I'm searching for the easiest way, so a predefined javascript function would be the best but I didn't found yet anything, here is what I have so far but I don't think that this is a good way:
function negative(number) {
if (number.match(/^-\d+$/)) {
return true;
} else {
return false;
}
}
This question is related to
javascript
negative-number
If you really want to dive into it and even need to distinguish between -0
and 0
, here's a way to do it.
function negative(number) {
return !Object.is(Math.abs(number), +number);
}
console.log(negative(-1)); // true
console.log(negative(1)); // false
console.log(negative(0)); // false
console.log(negative(-0)); // true
function negative(n) {
return n < 0;
}
Your regex should work fine for string numbers, but this is probably faster. (edited from comment in similar answer above, conversion with +n
is not needed.)
In ES6 you can use Math.sign function to determine if,
1. its +ve no
2. its -ve no
3. its zero (0)
4. its NaN
console.log(Math.sign(1)) // prints 1
console.log(Math.sign(-1)) // prints -1
console.log(Math.sign(0)) // prints 0
console.log(Math.sign("abcd")) // prints NaN
This is an old question but it has a lot of views so I think that is important to update it.
ECMAScript 6 brought the function Math.sign()
, which returns the sign of a number (1 if it's positive, -1 if it's negative) or NaN if it is not a number. Reference
You could use it as:
var number = 1;
if(Math.sign(number) === 1){
alert("I'm positive");
}else if(Math.sign(number) === -1){
alert("I'm negative");
}else{
alert("I'm not a number");
}
How about something as simple as:
function negative(number){
return number < 0;
}
The * 1
part is to convert strings to numbers.
Source: Stackoverflow.com