Advertisement
Advertisement


Convert a positive number to negative in C#


Question

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?

2016/02/04
1
142
2/4/2016 2:36:30 PM

Accepted Answer

How about

myInt = myInt * -1

2012/01/24
456
1/24/2012 11:13:11 PM


int negInt = -System.Math.Abs(myInt)
2011/08/01

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

var positive = 6;
var negative = -positive;
2009/08/28

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.

2009/08/28

The easy way:

myInt *= -1;
2009/08/28

int negInt = 0 - myInt;

Or guaranteed to be negative.

int negInt = -System.Math.Abs(someInt);
2009/08/28

Source: https://stackoverflow.com/questions/1348080
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]