Reputation: 3162
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?
Upvotes: 61
Views: 106010
Reputation: 104670
There are couple of ways to do this:
Built in function Math.Abs(Int)
Use * -1
like posNum *= - 1
Upvotes: 0
Reputation: 2667
If you're using int or long, this is the fastest way I've found to force a positive value:
int negativeIntValue = -1234567890;
int positiveIntValue = negativeIntValue < 0 ? ~negativeIntValue + 1 : negativeIntValue;
// = 1234567890
long negativeLongValue = -1234567890;
long positiveLongValue = negativeLongValue < 0 ? ~negativeLongValue + 1 : negativeLongValue ;
// = 1234567890
Upvotes: 0
Reputation: 609
Behind System.Math.Abs
:
int abs(int value)
{
if(value < 0) // If value is negative
{
return value * -1; // then return positive of value
}
return value; // else return same value
}
Some fun mini Version:
int abs_mini(int value)
{
return value < 0 ? value * -1 : value;
}
Lets use like that:
Console.WriteLine( abs(-3) ); // 3
Console.WriteLine( abs(-2) ); // 2
Console.WriteLine( abs(-1) ); // 1
Console.WriteLine( abs(0) ); // 0
Console.WriteLine( abs(1) ); // 1
Console.WriteLine( abs(2) ); // 2
Console.WriteLine( abs(3) ); // 3
Live action: https://rextester.com/OAAQ92244
Upvotes: 0
Reputation: 134
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
Upvotes: 0
Reputation: 571
Yet another way with Math.CopySign:
var negativeNum = -5;
var positiveNum = Math.CopySign(negativeNum, 1); // 5
Upvotes: 0