Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a positive number to negative in C#

Tags:

c#

People also ask

How do you convert a negative number to a positive number in C?

to convert this into positive number I used the abs() method as: a = abs(a);

How do you turn a negative into a positive?

All you have to do just multiply a negative value with -1 and it will return the positive number instead of the negative.

How do I make integers negative in C++?

Assuming the processor is at least somewhat competent and has sizeof(int) == sizeof(Cpu_register) , then a "make this number negative" will be a single instruction (usually called neg ) [well, may need the value loading and storing too, but if you are using the variable for anything else, it can remain after the load, ...


How about

myInt = myInt * -1


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

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

- 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.