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++;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With