How to check if a number is negative?

JavascriptNegative Number

Javascript Problem Overview


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 find anything yet. 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;
  }
}

Javascript Solutions


Solution 1 - Javascript

Instead of writing a function to do this check, you should just be able to use this expression:

(number < 0)

Javascript will evaluate this expression by first trying to convert the left hand side to a number value before checking if it's less than zero, which seems to be what you wanted.


Specifications and details

The behavior for x < y is specified in §11.8.1 The Less-than Operator (<), which uses §11.8.5 The Abstract Relational Comparison Algorithm.

The situation is a lot different if both x and y are strings, but since the right hand side is already a number in (number < 0), the comparison will attempt to convert the left hand side to a number to be compared numerically. If the left hand side can not be converted to a number, the result is false.

Do note that this may give different results when compared to your regex-based approach, but depending on what is it that you're trying to do, it may end up doing the right thing anyway.

  • "-0" < 0 is false, which is consistent with the fact that -0 < 0 is also false (see: signed zero).
  • "-Infinity" < 0 is true (infinity is acknowledged)
  • "-1e0" < 0 is true (scientific notation literals are accepted)
  • "-0x1" < 0 is true (hexadecimal literals are accepted)
  • " -1 " < 0 is true (some forms of whitespaces are allowed)

For each of the above example, the regex method would evaluate to the contrary (true instead of false and vice versa).

References
See also

Appendix 1: Conditional operator ?:

It should also be said that statements of this form:

if (someCondition) {
   return valueForTrue;
} else {
   return valueForFalse;
}

can be refactored to use the ternary/conditional ?: operator (§11.12) to simply:

return (someCondition) ? valueForTrue : valueForFalse;

Idiomatic usage of ?: can make the code more concise and readable.


Appendix 2: Type conversion functions

Javascript has functions that you can call to perform various type conversions.

Something like the following:

if (someVariable) {
   return true;
} else {
   return false;
}

Can be refactored using the ?: operator to:

return (someVariable ? true : false);

But you can also further simplify this to:

return Boolean(someVariable);

This calls Boolean as a function (§15.16.1) to perform the desired type conversion. You can similarly call Number as a function (§15.17.1) to perform a conversion to number.

Solution 2 - Javascript

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.)

Solution 3 - Javascript

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");
}

Solution 4 - Javascript

How about something as simple as:

function negative(number){
    return number < 0;
}

The * 1 part is to convert strings to numbers.

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

An nice way that also checks for positive and negative also...

function ispositive(n){
    return 1/(n*0)===1/0
}

console.log( ispositive(10) )  //true
console.log( ispositive(-10) )  //false
console.log( ispositive(0) )  //true
console.log( ispositive(-0) )  //false

essentially compares Infinity with -Infinity because 0===-0// true

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam HalaszView Question on Stackoverflow
Solution 1 - JavascriptpolygenelubricantsView Answer on Stackoverflow
Solution 2 - JavascriptbcherryView Answer on Stackoverflow
Solution 3 - JavascriptIván Rodríguez TorresView Answer on Stackoverflow
Solution 4 - JavascriptWolphView Answer on Stackoverflow
Solution 5 - JavascriptJTeamView Answer on Stackoverflow
Solution 6 - JavascriptHao WuView Answer on Stackoverflow
Solution 7 - Javascripttreeseal7View Answer on Stackoverflow