Search code examples
c#optimizationmathematical-optimization

Reduce one from absolute value?


I have an integer that needs its absolute value to be reduced by one.

Is there a shorter way than this:

if(number > 0) number--; else if (number < 0) number++;

Solution

  • Even shorter:

    number -= Math.Sign(number);
    

    Math.Sign returns -1, 0, or 1 depending on the sign of the specified value.

    Extension Method

    Since you say you face this situation a lot it might be beneficial to make this an extension method to better express your intent:

    public static int ReduceFromAbsoluteValue(this int number, int reduceValue)
    {
        return number - Math.Sign(number) * reduceValue;
    }
    
    4.ReduceFromAbsoluteValue(1);  // 3
    -4.ReduceFromAbsoluteValue(1); // -3
    0.ReduceFromAbsoluteValue(1);  // 0
    

    Alternatively name this AddToAbsoluteValue and change it to add the value.