How to convert negative number to positive in c#?

c#
30,744

Solution 1

Other people have provided Math.Abs as a solution. I don't know whether this inlines Math.Abs or not... But measure the performance gain from something like this vs Math.Abs:

int d = X > 0 ? X : -X; 

to verify that it's really worth it.

if Math.Abs throws an OverflowException. You can force this in the straight C# as well using checked arithmetic:

int d = X > 0 ? X : checked(-X);

EDIT: I ran some quick tests on different methods you can use:

Math.Abs(i)                    5839 ms     Factor 1
i > 0 ? i : -i                 6395 ms     Factor 1.09
(i + (i >> 31)) ^ (i >> 31)    5053 ms     Factor 0.86

Solution 2

You need to use Math.Abs()

You will have to convert every number that may be negative into a positive value like so

var result = 5 - (Math.Abs(-5))

Solution 3

Try Math.Abs this will solve the purpose.

So before applying any arithmetic operation you should apply Math.Abs(value) which will convert your negative value to positive.

class Program
   {
       static void Main()
       {
           //
           // Compute two absolute values.
           //
           int value1 = -1000;
           int value2 = 20;
           int abs1 = Math.Abs(value1);
           int abs2 = Math.Abs(value2);
           //
           // Write integral results.
           //
           Console.WriteLine(value1);
           Console.WriteLine(abs1);
           Console.WriteLine(value2);
           Console.WriteLine(abs2);
        }
    }
Share:
30,744
owt
Author by

owt

Updated on June 21, 2020

Comments

  • owt
    owt over 2 years

    Where taking away a minus value i.e. 5 - (-5), we are working this out as 10, which yes, mathematically it is correct.

    But in this case, our logic should treat each number as a positive and not minus negative numbers. It should be 5 - (-5) = 0 as per our requirement.