Always return positive value
C#MathC# 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