anon
anon

Reputation:

Convert a positive number to negative in C#

You can convert a negative number to positive like this:

int myInt = System.Math.Abs(-5);

Is there an equivalent method to make a positive number negative?

Upvotes: 141

Views: 419190

Answers (22)

Clive Galway
Clive Galway

Reputation: 504

As previously mentioned, just multiplying by -1 is not cool, as int.MinValue * -1 == int.MinValue

It really depends on your application, but for mine (Inverting Joystick axes) I want to ensure that all extremes are still reachable, and maintain as much fidelity as possible.
To this end, I map Max <--> Min and everything in-between gets a * -1
Using this technique, -32767 is unreachable when inverting.

    private static int Invert(int value)
    {
        if (value == int.MaxValue) return int.MinValue;
        if (value == int.MinValue) return int.MaxValue;
        return value * -1;
    }

Upvotes: 2

Eduardo Rauchbach
Eduardo Rauchbach

Reputation: 427

Just something that I want to share.

public decimal NumberReevaluate(decimal number, bool isPositive)
{
    var tempNumber = System.Math.Abs(number);
    return isPositive ? tempNumber : -tempNumber;
}

Upvotes: 0

Sam Jones
Sam Jones

Reputation: 4618

Converting a number from positive to negative, or negative to positive:

public static decimal Reverse(this decimal source)
{
     return source * decimal.MinusOne;
}

Upvotes: 2

CMS
CMS

Reputation: 3757

I use myInt = -myInt;

So simple and easy

If you want to have only positive

myInt = myInt>0 ? myInt : -myInt;

Upvotes: 10

arunKr
arunKr

Reputation: 17

Use binary and to remove the last bit which is responsible for negative sign.

Or use binary or to add sign to a datatype.

This soln may sound absurd and incomplete but I can guarantee this is the fastest method.

If you don't experiment with what I have posted this post may look crap :D

Eg for int:

Int is 32 bit datatype so the last bit (32th one) determines the sign.

And with a value which has 0 in the 32 place and rest 1. It will convert negative no to +ve.

For just the opposite or with a value with 1 in 32th place and rest 0.

Upvotes: -1

bryanbcook
bryanbcook

Reputation: 17963

How about

myInt = myInt * -1

Upvotes: 571

Jim W
Jim W

Reputation: 4970

int myNegInt = System.Math.Abs(myNumber) * (-1);

Upvotes: 282

JDunkerley
JDunkerley

Reputation: 12495

int negInt = -System.Math.Abs(myInt)

Upvotes: 145

Broken_Window
Broken_Window

Reputation: 2093

Maybe this?

int n;

.... some coding....

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

Upvotes: 4

Detsuna Acalibar
Detsuna Acalibar

Reputation: 5

X=*-1 may not work on all compilers... since it reads a 'multiply' 'SUBTRACT' 1 instead of NEGATIVE The better alt is X=(0-X), [WHICH IS DIFF FROM X-=X]

Upvotes: -3

daveidmx
daveidmx

Reputation: 371

Even though I'm way late to the party here, I'm going to chime in with some useful tricks from my hardware days. All of these assume 2's compliment representation for signed numbers.

int negate = ~i+1;
int positiveMagnitude = (i ^ (i>>31)) - (i>>31);
int negativeMagnitude = (i>>31) - (i ^ (i>>31));

Upvotes: 6

Charles Bretana
Charles Bretana

Reputation: 146409

EDIT: This is wrong for positive inputs... I made mistake of forgetting that the rest of the bits in -x (2s-Complement value) are the 'opposite' of their value in +x, not the same. SO simply changing the sign bit will NOT work for positive numbers.

I'll leave this here for in for purposes...

Or the tricky way ( I think )...

int y = x | ~int.MaxValue;

cause int.MaxValue is 0111 1111 1111 1111 1111 1111 1111 1111

so

~int.MaxValue is      1000 0000 0000 0000 0000 0000 0000 0000

and therefore any int32 Or'ed with that will put a 1 in the sign bit, (making it negative), and leave all the other bits the same...

EDIT: actually, Since the 1000 0000 0000 0000 0000 0000 0000 0000 is actually the Minvalue, this should also work:

   int y = x | int.MinValue; // or, to do it to itself,
   x |= int.MinValue;

Upvotes: 6

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

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.

Upvotes: 46

MusiGenesis
MusiGenesis

Reputation: 75296

Just for fun:

int negativeInt = int.Parse(String.Format("{0}{1}", 
    "-", positiveInt.ToString()));

Update: the beauty of this approach is that you can easily refactor it into an exception generator:

int negativeInt = int.Parse(String.Format("{0}{1}", 
    "thisisthedumbestquestioninstackoverflowhistory", positiveInt.ToString()));

Upvotes: 5

Mike Dunlavey
Mike Dunlavey

Reputation: 40649

Just for more fun:

int myInt = Math.Min(hisInt, -hisInt);

int myInt = -(int)Math.Sqrt(Math.Pow(Math.Sin(1), 2) + Math.Pow(Math.Cos(-1), 2))
            * Math.Abs(hisInt);

Upvotes: 6

MusiGenesis
MusiGenesis

Reputation: 75296

long negativeNumber = (long)positiveInt - (long)(int.MaxValue + 1);

Nobody said it had to be any particular negative number.

Upvotes: 4

Guffa
Guffa

Reputation: 700152

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);

Upvotes: 12

impomatic
impomatic

Reputation: 131

int myInt = - System.Math.Abs(-5);

Upvotes: 3

Joe White
Joe White

Reputation: 97656

The same way you make anything else negative: put a negative sign in front of it.

var positive = 6;
var negative = -positive;

Upvotes: 104

Warren Pena
Warren Pena

Reputation: 572

Multiply it by -1.

Upvotes: 2

driis
driis

Reputation: 164281

The easy way:

myInt *= -1;

Upvotes: 24

TJ L
TJ L

Reputation: 24452

int negInt = 0 - myInt;

Or guaranteed to be negative.

int negInt = -System.Math.Abs(someInt);

Upvotes: 20

Related Questions