How do I check if a number is positive or negative in C#?

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
Share:
226,980

Related videos on Youtube

user9969
Author by

user9969

Updated on November 29, 2020

Comments

  • user9969
    user9969 about 2 years

    How do I check if a number is positive or negative in C#?

    • Muhammad Ayyaz over 2 years
      Useful Question.
  • SirDarius
    SirDarius about 12 years
    I 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
    Grant Crofton about 12 years
    What about poor old negative zero?!
  • Powerlord
    Powerlord about 12 years
    (If it wasn't obvious, this was intended to be humor)
  • slashmais
    slashmais about 12 years
    at 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
    Jesse C. Slicer about 12 years
    Internally, it should instantiate a class which implements ISignDeterminator using a SignDeterminatorFactory.
  • slashmais
    slashmais about 12 years
    Incomplete: you should check for IsNaN() as well ;)
  • Jeff Yates
    Jeff Yates about 12 years
    @slashmais: On an int?! What magical land of C# are you working in?
  • andriy
    andriy about 12 years
    For .NET 4.0 you should add IsImaginary.
  • Tanmoy
    Tanmoy about 12 years
    Wow didn't know this exists.What happens for NaN?
  • gnovice
    gnovice about 12 years
    @Tanmoy: Looks like it will throw an exception in that case.
  • Michael Stum
    Michael Stum about 12 years
    You can also use System.Data.OracleClient to connect to an Oracle database and execute PL/SQL to determine if a number is negative.
  • Powerlord
    Powerlord about 12 years
    @Eric: No, because it will throw an OverflowException if num is MinValue for whatever type is passed in (Int16, Int32, Int64). Results are even worse for floating point values, where they could also be NaN, since NaN != NaN.
  • AndrewC
    AndrewC over 11 years
    But 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
    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
    Memet Olsen almost 8 years
    You should add <summary> commentary in your code so it becomes more reliable, consistent, decent, accessable, stable, robust, solid, safe and clear.
  • Episodex
    Episodex over 7 years
    This is not C# though
  • Tim Čas
    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, and IsPositiveCheckerFactoryInterface, though.
  • damianostre about 7 years
    I tried it out. My program ran eventually out of memory. Could there be a leak in your code?
  • ImGeorge
    ImGeorge about 7 years
    check for -ve / +ve decimals as well
  • Will
    Will almost 7 years
    @ThomasTempelmann there was indeed a memory leak, as p was malloc()'d but never free()'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
    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
    Will almost 7 years
    I 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
    Will almost 7 years
    There we go, reverted, flagged, and downvoted. I wasn't aware this was a joke.
  • Vahid Amiri
    Vahid Amiri over 6 years
    Just used this in my Hello World console app. 10/10 would do it again.
  • T.Todua
    T.Todua over 4 years
    no, OP asked if is positive or is negative not is (positive or negative)
  • Jude Bautista about 4 years
    0 still positive
  • VoronoiPotato
    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
    Dragonrage almost 4 years
    you 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 a return result; somewhere in there at the end so it will actually return the result.
  • NetherGranite
    NetherGranite over 3 years
    @T.Todua I believe that was the joke.
  • Paul
    Paul over 2 years
    I didn't expect to find a useful answer below this question, but this is actually what I was looking for. Thanks.
  • mw509
    mw509 about 2 years
    I 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
    Timothy Kanski almost 2 years
    Well played sir
  • Jaryn
    Jaryn 8 months
    It will break for the edge case scenario. For example for int: Int32.MinValue: -2147483648.