104

Lets say i have the value 10 assigned to a variable;

var values = 10;

and i want to run a specific function if the value is a positive

if(values = +integer){ 
    //do something with positive 
} else { 
    //do something with negative values 
}

How would this be achieved?

2
  • I assume that you are incrementing/decrementing the variable. If so why don't you write an if condition to check the value after incrementing/decrementing the variable?
    – Sagar V
    Commented Aug 12, 2011 at 8:50
  • 17
    Upvoted this question - I had a mega brain fart today, trying to figure out how to determine if a number was positive or negative in Javascript today. I guess it's about time to take a break from programming.....
    – user677526
    Commented Jul 24, 2013 at 20:19

18 Answers 18

218
if (values > 0) {
    // Do Something
}
4
  • 5
    Just want to add one comment: I noticed that the original question asked not only if the value was positive, but if it was a positive integer. To address the second requirement I created a new answer
    – stevendesu
    Commented Jul 14, 2014 at 15:37
  • Be aware of numbers like -2.2737367544323206e-13 (i.e.: almost zero). I thought this discussion insteresting: stackoverflow.com/questions/588004/…
    – thicolares
    Commented Oct 10, 2014 at 2:42
  • 4
    this answer does not check if the value is a positive integer where integer is a whole number and not a fraction
    – Reinsbrain
    Commented Apr 14, 2015 at 23:12
  • 2
    just a note here: tried that today to see if I have a positive number (int or float) and it also evaluated to true for values=true. So... check if values is actually a boolean!
    – wullxz
    Commented Sep 5, 2015 at 2:49
34

Am I the only one who read this and realized that none of the answers addressed the "integer" part of the question?

The problem

var myInteger = 6;
var myFloat = 6.2;
if( myInteger > 0 )
    // Cool, we correctly identified this as a positive integer
if( myFloat > 0 )
    // Oh, no! That's not an integer!

The solution

To guarantee that you're dealing with an integer, you want to cast your value to an integer then compare it with itself.

if( parseInt( myInteger ) == myInteger && myInteger > 0 )
    // myInteger is an integer AND it's positive
if( parseInt( myFloat ) == myFloat && myFloat > 0 )
    // myFloat is NOT an integer, so parseInt(myFloat) != myFloat

Some neat optimizations

As a bonus, there are some shortcuts for converting from a float to an integer in JavaScript. In JavaScript, all bitwise operators (|, ^, &, etc) will cast your number to an integer before operating. I assume this is because 99% of developers don't know the IEEE floating point standard and would get horribly confused when "200 | 2" evaluated to 400(ish). These shortcuts tend to run faster than Math.floor or parseInt, and they take up fewer bytes if you're trying to eke out the smallest possible code:

if( myInteger | 0 == myInteger && myInteger > 0 )
    // Woot!
if( myFloat | 0 == myFloat && myFloat > 0 )
    // Woot, again!

But wait, there's more!

These bitwise operators are working on 32-bit signed integers. This means the highest bit is the sign bit. By forcing the sign bit to zero your number will remain unchanged only if it was positive. You can use this to check for positiveness AND integerness in a single blow:

// Where 2147483647 = 01111111111111111111111111111111 in binary
if( (myInteger & 2147483647) == myInteger )
    // myInteger is BOTH positive and an integer
if( (myFloat & 2147483647) == myFloat )
    // Won't happen
* note bit AND operation is wrapped with parenthesis to make it work in chrome (console)

If you have trouble remembering this convoluted number, you can also calculate it before-hand as such:

var specialNumber = ~(1 << 31);

Checking for negatives

Per @Reinsbrain's comment, a similar bitwise hack can be used to check for a negative integer. In a negative number, we do want the left-most bit to be a 1, so by forcing this bit to 1 the number will only remain unchanged if it was negative to begin with:

// Where -2147483648 = 10000000000000000000000000000000 in binary
if( (myInteger | -2147483648) == myInteger )
    // myInteger is BOTH negative and an integer
if( (myFloat | -2147483648) == myFloat )
    // Won't happen

This special number is even easier to calculate:

var specialNumber = 1 << 31;

Edge cases

As mentioned earlier, since JavaScript bitwise operators convert to 32-bit integers, numbers which don't fit in 32 bits (greater than ~2 billion) will fail

You can fall back to the longer solution for these:

if( parseInt(123456789000) == 123456789000 && 123456789000 > 0 )

However even this solution fails at some point, because parseInt is limited in its accuracy for large numbers. Try the following and see what happens:

parseInt(123123123123123123123); // That's 7 "123"s

On my computer, in Chrome console, this outputs: 123123123123123130000

The reason for this is that parseInt treats the input like a 64-bit IEEE float. This provides only 52 bits for the mantissa, meaning a maximum value of ~4.5e15 before it starts rounding

7
  • I should note that this will not work for integers larger than 2147483647. For example: 99999999999 & 2147483647 = 1215752191
    – stevendesu
    Commented Jul 10, 2014 at 19:19
  • Actually the question does not ask to check if it is an integer type and if that integer is positive. It asks if 'var values = 10' is a positive integer as shown in the code provided, which is all we get to work with. Commented Jul 16, 2014 at 21:34
  • 3
    @PeterKelly, I'm afraid I really don't understand how the question was ambiguous. He said: "How to check the value given is a positive or negative integer?" - and every response answered the "positive" part, but not the "integer" part. If nothing else my answer is a valid solution to his problem and a good lesson on JavaScript so probably doesn't deserve a down vote.
    – stevendesu
    Commented Jul 17, 2014 at 13:34
  • 1
    @stevendesu is right. The integer is part of the question. Commented Apr 9, 2015 at 5:47
  • 2
    @stevendesu this should be the accepted answer, especially if you could modify the answer to also handle cases of negative integers. good work and thanks for the great example
    – Reinsbrain
    Commented Apr 14, 2015 at 23:24
23

To just check, this is the fastest way, it seems:

var sign = number > 0 ? 1 : number == 0 ? 0 : -1; 
//Is "number": greater than zero? Yes? Return 1 to "sign".
//Otherwise, does "number" equal zero?  Yes?  Return 0 to "sign".  
//Otherwise, return -1 to "sign".

It tells you if the sign is positive (returns 1), or equal to zero (returns 0), and otherwise (returns -1). This is a good solution because 0 is not positive, and it is not negative, but it may be your var.

Failed attempt:

var sign = number > 0 ? 1 : -1;

...will count 0 as a negative integer, which is wrong.

If you're trying to set up conditionals, you can adjust accordingly. Here's are two analogous example of an if/else-if statement:

Example 1:

number = prompt("Pick a number?");
if (number > 0){
  alert("Oh baby, your number is so big!");}
else if (number == 0){
  alert("Hey, there's nothing there!");}
else{
  alert("Wow, that thing's so small it might be negative!");}

Example 2:

number = prompt("Pick a number?");

var sign = number > 0 ? 1 : number == 0 ? 0 : -1;

if (sign == 1){
  alert("Oh baby, your number is so big!" + " " + number);}
else if (sign == 0){
  alert("Hey, there's nothing there!" + " " + number);}
else if (sign == -1){
  alert("Wow, that thing's so small it might be negative!" + " " + number);}
2
  • 1
    Why not use Math.sign() to find the sign of the number? Commented Nov 19, 2021 at 10:31
  • I didn't know that function existed, Bronze. @Bronzdragon, any-which-way-you-can, I guess. ^;) Commented Nov 20, 2021 at 12:53
18

I thought here you wanted to do the action if it is positive.

Then would suggest:

if (Math.sign(number_to_test) === 1) {
     function_to_run_when_positive();
}
5
  • 3
    The only correct awnser when it comes to positive/negative numbers.
    – dbf
    Commented May 8, 2017 at 21:10
  • Best answer! Valid for any number types.
    – felansu
    Commented Mar 29, 2018 at 9:49
  • 1
    Just fyi, Math.sign() isn't supported in IE 11 or prior Commented Jan 14, 2020 at 21:51
  • 1
    Math.sign documentation fyi. Commented May 7, 2020 at 10:25
  • 1
    To check if the value is negative Math.sign(valueToTest) === -1
    – Seno
    Commented Jul 6, 2021 at 10:25
10

1 Checking for positive value

In javascript simple comparison like: value >== 0 does not provide us with answer due to existence of -0 and +0 (This is concept has it roots in derivative equations) Bellow example of those values and its properties:

var negativeZero = -0;
var negativeZero = -1 / Number.POSITIVE_INFINITY;
var negativeZero = -Number.MIN_VALUE / Number.POSITIVE_INFINITY;

var positiveZero = 0;
var positiveZero = 1 / Number.POSITIVE_INFINITY;
var positiveZero = Number.MIN_VALUE / Number.POSITIVE_INFINITY;

-0 === +0                     // true
1 / -0                        // -Infinity
+0 / -0                       // NaN
-0 * Number.POSITIVE_INFINITY // NaN

Having that in mind we can write function like bellow to check for sign of given number:

function isPositive (number) {
    if ( number > 0 ) { 
        return true;
    }
    if (number < 0) {
        return false;
    }
    if ( 1 / number === Number.POSITIVE_INFINITY ) {
        return true;
    }
    return false;
}

2a Checking for number being an Integer (in mathematical sense)

To check that number is an integer we can use bellow function:

function isInteger (number) {
    return parseInt(number) === number;
}
//* in ECMA Script 6 use Number.isInteger

2b Checking for number being an Integer (in computer science)

In this case we are checking that number does not have any exponential part (please note that in JS numbers are represented in double-precision floating-point format) However in javascript it is more usable to check that value is "safe integer" (http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) - to put it simple it means that we can add/substract 1 to "safe integer" and be sure that result will be same as expected from math lessons. To illustrate what I mean, result of some unsafe operations bellow:

Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2;          // true
Number.MAX_SAFE_INTEGER * 2 + 1 === Number.MAX_SAFE_INTEGER * 2 + 4;  // true

Ok, so to check that number is safe integer we can use Number.MAX_SAFE_INTEGER / Number.MIN_SAFE_INTEGER and parseInt to ensure that number is integer at all.

function isSafeInteger (number) {
    return parseInt(number) === number
    && number <== Number.MAX_SAFE_INTEGER
    && number >== Number.MIN_SAFE_INTEGER
}
//* in ECMA Script 6 use Number.isSafeInteger
1
  • 1
    +1 I think this is better than my answer as it covers the edge cases of negative zero and MAX_SAFE_INTEGER. My answer gave a cool and high-performance short-hand solution, but just glossed over the edge cases.
    – stevendesu
    Commented Aug 24, 2017 at 14:42
7

simply write:

if(values > 0){
//positive
}
else{
//negative
}
6
if(values >= 0) {
 // as zero is more likely positive than negative
} else {

}
5
if ( values > 0 ) {
    // Yeah, it's positive
}
0
5
if ( values > 0 ) {
    //you got a positive value
}else{
    //you got a negative or zero value    
}
5

To check a number is positive, negative or negative zero. Check its sign using Math.sign() method it will provide you -1,-0,0 and 1 on the basis of positive negative and negative zero or zero numbers

 Math.sign(-3) // -1
 Math.sign(3) // 1
 Math.sign(-0) // -0
 Math.sign(0) // 0
5

I know it's been some time, but there is a more elegant solution. From the mozilla docs:

Math.sign(parseInt(-3))

It will give you -1 for negative, 0 for zero and 1 for positive.

4

You can use the shifting bit operator, but it won't get the difference between -0 and +0 like Math.sign(x) does:

let num = -45;
if(num >> 31 === -1)
    alert('Negative number');
else
    alert('Positive number');

https://jsfiddle.net/obxptgze/

3

Positive integer:

if (parseInt(values, 10) > 0) {

}
0

I use in this case and it works :)

var pos = 0; 
var sign = 0;
var zero = 0;
var neg = 0;
for( var i in arr ) {
    sign = arr[i] > 0 ? 1 : arr[i] == 0 ? 0 : -1;
    if (sign === 0) {
        zero++; 
    } else if (sign === 1 ) {
        pos++;
    } else {
        neg++;
    }
}
0

You should first check if the input value is interger with isNumeric() function. Then add the condition or greater than 0. This is the jQuery code for it.

function isPositiveInteger(n) {
        return ($.isNumeric(n) && (n > 0));
}
0

The Math.sign() function returns either a positive or negative +/- 1, indicating the sign of a number passed into the argument. If the number passed into Math.sign() is 0, it will return a +/- 0. Note that if the number is positive, an explicit (+) will not be returned.

console.log(Math.sign(-3));
let num = -123;
let val = Math.sign(num);
if(val === -1){
    console.log(num + " is negative number");
}else{
    console.log(num + " is posative number");
}
-1

For checking positive integer:

var isPositiveInteger = function(n) {
        return ($.isNumeric(n)) && (Math.floor(n) == n) && (n > 0); 
}
-2

Starting from the base that the received value is a number and not a string, what about use Math.abs()? This JavaScript native function returns the absolute value of a number:

Math.abs(-1) // 1

So you can use it this way:

var a = -1;
if(a == Math.abs(a)){
    // false 
}

var b = 1;   
if(b == Math.abs(b)){
    // true
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.