Search code examples
c#mathnumbersdouble

Math function to remove minus


If input value is -0.088 and I want take from x = 0.8 like this 0.8 - -0.088 but in result I want get 0.712 instead of 0.888 as it would be with minus 0.8 - 0.088.

How to remove minus from number without direct string processing, can I use some Math function for such case:

    double x1 = 0.8;
    double x2 = 0.8;
    double a = -0.088;
    double b = 0.088;

    x1 = (x1 - a); 
    x2 = (x2 - b); 

    Console.WriteLine("0.8 minus -0.088 equals to [ " + x1 + 
                 " ]\r\n0.8 minus 0.088 equals to [ " + x2 + " ]");

result:

 0.8 minus -0.088 equals to [ 0.888 ]
 0.8 minus 0.088 equals to [ 0.712 ]

desired result:

0.8 minus -0.088 equals to [ 0.712 ]
0.8 minus 0.088 equals to [ 0.712 ]

Solution

  • Removing minus corresponds to the mathematical concept of absolute value. .NET implementation of this function is Math.Abs method:

    x1 = (x1 - Math.Abs(a));