Chris
Chris

Reputation: 3162

Always return positive value

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

Answers (11)

Alireza
Alireza

Reputation: 104670

There are couple of ways to do this:

  1. Built in function Math.Abs(Int)

  2. Use * -1 like posNum *= - 1

Upvotes: 0

Sean
Sean

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

Gray Programmerz
Gray Programmerz

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

Ankit Gupta
Ankit Gupta

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

BorisSh
BorisSh

Reputation: 571

Yet another way with Math.CopySign:

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

Upvotes: 0

MVijayvargia
MVijayvargia

Reputation: 349

Use this :

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

Upvotes: 10

Sunil Game
Sunil Game

Reputation: 29

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

Upvotes: 0

Shai
Shai

Reputation: 25619

Use System.Math.Abs as documented here.

Upvotes: 147

Mark Entingh
Mark Entingh

Reputation: 681

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

Upvotes: 2

Aan
Aan

Reputation: 12890

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.

Upvotes: 4

SLaks
SLaks

Reputation: 887405

You're looking for Math.Abs.

Upvotes: 11

Related Questions