How do I check if a number is positive or negative in C#?
226,980
Solution 1
bool positive = number > 0;
bool negative = number < 0;
Solution 2
Of course no-one's actually given the correct answer,
num != 0 // num is positive *or* negative!
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);
}
}
Solution 4
The Math.Sign method is one way to go. It will return -1 for negative numbers, 1 for positive numbers, and 0 for values equal to zero (i.e. zero has no sign). Double and single precision variables will cause an exception (ArithmeticException) to be thrown if they equal NaN.
Solution 5
num < 0 // number is negative
Related videos on Youtube

Author by
user9969
Updated on November 29, 2020Comments
-
user9969 about 2 years
How do I check if a number is positive or negative in C#?
-
Muhammad Ayyaz over 2 yearsUseful Question.
-
-
SirDarius about 12 yearsI assume that this is a beginner, which we should try to help. Once you learn the right way -- check this for the wrong way thedailywtf.com/Articles/…
-
Grant Crofton about 12 yearsWhat about poor old negative zero?!
-
Powerlord about 12 years(If it wasn't obvious, this was intended to be humor)
-
slashmais about 12 yearsat first I could'nt believe the question on the main page, then I came here ... :) and this guy is not alone ... oh dear :)
-
Jesse C. Slicer about 12 yearsInternally, it should instantiate a class which implements
ISignDeterminator
using aSignDeterminatorFactory
. -
slashmais about 12 yearsIncomplete: you should check for IsNaN() as well ;)
-
Jeff Yates about 12 years@slashmais: On an
int
?! What magical land of C# are you working in? -
andriy about 12 yearsFor .NET 4.0 you should add
IsImaginary
. -
Tanmoy about 12 yearsWow didn't know this exists.What happens for NaN?
-
gnovice about 12 years@Tanmoy: Looks like it will throw an exception in that case.
-
Michael Stum about 12 yearsYou can also use System.Data.OracleClient to connect to an Oracle database and execute PL/SQL to determine if a number is negative.
-
Powerlord about 12 years@Eric: No, because it will throw an
OverflowException
ifnum
isMinValue
for whatever type is passed in (Int16
,Int32
,Int64
). Results are even worse for floating point values, where they could also beNaN
, sinceNaN != NaN
. -
AndrewC over 11 yearsBut then he has to check if the result of Math.Sign is positive or negative too! Does he use Math.Sign for that as well? ;)
-
Rob about 11 years@AndyC: I enjoyed the humor, but he should be doing equality comparison against the return value of
Math.Sign
(since it explicitly defines possible return values.) -
Memet Olsen almost 8 yearsYou should add <summary> commentary in your code so it becomes more reliable, consistent, decent, accessable, stable, robust, solid, safe and clear.
-
Episodex over 7 yearsThis is not C# though
-
Tim Čas over 7 years"Do not ever use this"? But it's enterprise-quality code, perfect for enterprise software! You're missing
IsPositiveChecker
,IsPositiveCheckerInterface
,IsPositiveCheckerFactory
, andIsPositiveCheckerFactoryInterface
, though. -
damianostre about 7 yearsI tried it out. My program ran eventually out of memory. Could there be a leak in your code?
-
ImGeorge about 7 yearscheck for -ve / +ve decimals as well
-
Will almost 7 years@ThomasTempelmann there was indeed a memory leak, as
p
wasmalloc()
'd but neverfree()
'd. I fixed this in my edit. -
damianostre almost 7 years@Will, well done for spotting this very obscure leak! Though I frown upon you changing the meaning of the original poster's introductory sentence. I still believe it's correct to call this the industry standard. Hence, to keep with the spirit of this answer, and with respect to the original poster, I've reverted your edit, okay?
-
Will almost 7 years@ThomasTempelmann Then the right solution was to correct the post to use the original sentence and the fixed code. With respect to the original poster, anyone who stumbles across this will experience rampant memory leaking. It appears from the comments above that you ran into this leak yourself. I don't think "the industry standard" has memory leaks, and I coudn't find anything to back up this being an industry standard. But I'll leave it and fix the code.
-
damianostre almost 7 years@Will, do I really need to state the obvious about the original post and my comments, which got upvotes while yours doesn't? (Spoiler: it has to do with sarcasm, and yours doesn't, which means you've killed the joke that bad existed here - or do you really think that this answer was meant to be taken seriously??)
-
Will almost 7 yearsI took it seriously; the sarcasm was non-obvious and this will confuse new users and non-native speakers. If it's not a serious answer, I'll just revert my edit and flag it as not an answer.
-
Will almost 7 yearsThere we go, reverted, flagged, and downvoted. I wasn't aware this was a joke.
-
Vahid Amiri over 6 yearsJust used this in my Hello World console app. 10/10 would do it again.
-
T.Todua over 4 yearsno, OP asked if
is positive or is negative
notis (positive or negative)
-
Jude Bautista about 4 years0 still positive
-
VoronoiPotato about 4 years@SimonFischer There are definitely branches of mathematics, computer science, also regular science which use a negative and positive zero. Chemists and physicists for example will sometimes use -0 for a number which was negative and rounded to zero. Definitions only have meaning within a context. When you treat the mathematical definitions you were taught as though they are truly universal you risk ending up in a different mathematical context where you are wrong.
-
Dragonrage almost 4 yearsyou are missing a set of parenthesis as '&' has a lower precedence than '==', so you should have
result = (Marshal.ReadByte(memory, 3) & 0x80) == 0;
instead. Also, you should have areturn result;
somewhere in there at the end so it will actually return the result. -
NetherGranite over 3 years@T.Todua I believe that was the joke.
-
Paul over 2 yearsI didn't expect to find a useful answer below this question, but this is actually what I was looking for. Thanks.
-
mw509 about 2 yearsI came looking for same thing. saw this and am like "ow!" expected something else. Why didnt I think of this. the pressure people! the pressure! lol
-
Timothy Kanski almost 2 yearsWell played sir
-
Jaryn 8 monthsIt will break for the edge case scenario. For example for int: Int32.MinValue: -2147483648.