Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++;
like image 812
Shimmy Weitzhandler Avatar asked Apr 19 '26 11:04

Shimmy Weitzhandler


1 Answers

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.

like image 76
David Sherret Avatar answered Apr 22 '26 02:04

David Sherret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!