Reputation: 8362
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?
Upvotes: 105
Views: 341591
Reputation: 3055
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/
Upvotes: 4
Reputation: 8055
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");
}
Upvotes: 1
Reputation: 2892
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.
Upvotes: 5
Reputation: 122
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
}
Upvotes: -2
Reputation: 51
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
Upvotes: 5
Reputation: 1081
For checking positive integer:
var isPositiveInteger = function(n) {
return ($.isNumeric(n)) && (Math.floor(n) == n) && (n > 0);
}
Upvotes: -1
Reputation: 889
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();
}
Upvotes: 17
Reputation: 6292
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));
}
Upvotes: 1
Reputation: 16771
Am I the only one who read this and realized that none of the answers addressed the "integer" part of the question?
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!
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
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);
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;
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
Upvotes: 34
Reputation: 2776
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++;
}
}
Upvotes: 0
Reputation: 101
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;
}
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
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
Upvotes: 10
Reputation: 4128
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);}
Upvotes: 23
Reputation: 5061
if ( values > 0 ) {
//you got a positive value
}else{
//you got a negative or zero value
}
Upvotes: 5
Reputation: 6981
if(values >= 0) {
// as zero is more likely positive than negative
} else {
}
Upvotes: 6