Always return positive value

C#Math

C# Problem Overview


I have a number it could be negative or positive but I simply want to return the positive value.

-4 -> 4
5 -> 5

I know I can do a simple if check, see if its zero then return it *-1 but I can't remember for the life of me what the actual Maths operator is!

Can anyone tell me what it is?

C# Solutions


Solution 1 - C#

Use System.Math.Abs as documented here.

Solution 2 - C#

You're looking for Math.Abs.

Solution 3 - C#

Use this :

int PositiveNo = System.Math.Abs(NegativeNoHere);

Solution 4 - C#

There is an overloaded method Math.Abs can be used in your case. It can take Double, Int16, Int32, Int64, SByte, Single or Decimal as an argument.

Solution 5 - C#

If you're working with floats in Unity, use Mathf.Abs

Solution 6 - C#

You can use Math.Abs like public static int Abs (int value);

Solution 7 - C#

Yet another way with Math.CopySign:

var negativeNum = -5;
var positiveNum = Math.CopySign(negativeNum, 1); // 5

Solution 8 - C#

OutputNumber = System.Math.Abs(Input_Number)

Or

if(Input_Number<0){
return Input_Number=Input_Number * -1;
}else{
   return Input_Number;
}

Both should works fine

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisView Question on Stackoverflow
Solution 1 - C#ShaiView Answer on Stackoverflow
Solution 2 - C#SLaksView Answer on Stackoverflow
Solution 3 - C#MVijayvargiaView Answer on Stackoverflow
Solution 4 - C#AanView Answer on Stackoverflow
Solution 5 - C#Mark EntinghView Answer on Stackoverflow
Solution 6 - C#Sunil GameView Answer on Stackoverflow
Solution 7 - C#BorisShView Answer on Stackoverflow
Solution 8 - C#Ankit GuptaView Answer on Stackoverflow