Convert Negative Numbers to Positive Numbers - High-Flying C# Coding Tips


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

Convert Negative Numbers to Positive Numbers

Here we'll look at a way of converting negative numbers to positive numbers.

Should you have a number, which happens to be a negative number, eg -5, and you want to convert that number into a positive number, ie 5 (+5), C# provides a method which will convert the number for you.

The Math.Abs() method will perform the conversion for you, it returns what is known as the absolute value of a number, that is the positive value of a number.


In this example, we create an integer called _number and give it a negative value of -5. Then we convert this negative number into a positive number in the integer called _positiveValue by calling the Math.Abs() method and passing the method the negative value.



// return the positive value of a number
int _number = -5;

// _positiveValue will equal 5;
int _positiveValue = Math.Abs(_number);