Problem
In C#, how can I determine whether an integer is positive or negative?
Asked by user9969
Solution #1
bool positive = number > 0;
bool negative = number < 0;
Answered by Simon Fischer
Solution #2
No one has supplied the correct answer, of course.
num != 0 // num is positive *or* negative!
Answered by tjm
Solution #3
OVERKILL!
public static class AwesomeExtensions
{
public static bool IsPositive(this int number)
{
return number > 0;
}
public static bool IsNegative(this int number)
{
return number < 0;
}
public static bool IsZero(this int number)
{
return number == 0;
}
public static bool IsAwesome(this int number)
{
return IsNegative(number) && IsPositive(number) && IsZero(number);
}
}
Answered by hunter
Solution #4
One option is to use the Math.Sign technique. For negative numbers, it will return -1, for positive numbers, 1 and for zero values, it will return 0. (i.e. zero has no sign). If a double or single precision variable equals NaN, an exception (ArithmeticException) will be thrown.
Answered by gnovice
Solution #5
num < 0 // number is negative
Answered by Lou Franco
Post is based on https://stackoverflow.com/questions/4099366/how-do-i-check-if-a-number-is-positive-or-negative-in-c