Convert a positive number to negative in C#

Convert a positive number to negative in C#

Asked on December 20, 2018 in C#.
Add Comment


  • 3 Answer(s)

    Note to everyone who responded with

    - Math.Abs(myInteger)

    or

    0 - Math.Abs(myInteger)

    or

    Math.Abs(myInteger) * -1

    as a way to keep negative numbers negative and turn positive ones negative.

    This approach has a single flaw. It doesn’t work for all integers. The range of Int32 type is from “-231” to “231 – 1.” It means there’s one more “negative” number. Consequently, Math.Abs(int.MinValue) throws an OverflowException.

    The correct way is to use conditional statements:

    int neg = n < 0 ? n : -n;

    This approach works for “all” integers.

    Answered on January 15, 2019.
    Add Comment

    To switch the sign of an integer, you just use the sign operator:

    myInt = -myInt;

    To make it negative regardless if the original value is negative or not, you first use the Abs method:

    myInt = -Math.Abs(myInt);
    Answered on January 15, 2019.
    Add Comment
    int negInt = 0 - myInt;

    //Or guaranteed to be negative.

    int negInt = -System.Math.Abs(someInt);
    Answered on January 28, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.