Convert a positive number to negative in C#
myInt = myInt * -1
int myNegInt = System.Math.Abs(myNumber) * (-1);
Read more... Read less...
int negInt = -System.Math.Abs(myInt)
The same way you make anything else negative: put a negative sign in front of it.
var positive = 6; var negative = -positive;
Note to everyone who responded with
0 - Math.Abs(myInteger)
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
The correct way is to use conditional statements:
int neg = n < 0 ? n : -n;
This approach works for "all" integers.
The easy way:
myInt *= -1;
int negInt = 0 - myInt;
Or guaranteed to be negative.
int negInt = -System.Math.Abs(someInt);