Convert to absolute value in Objective-C

Objective C

Objective C Problem Overview


How do I convert a negative number to an absolute value in Objective-C?

i.e.

-10

becomes

10?

Objective C Solutions


Solution 1 - Objective C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

Solution 2 - Objective C

You can use this function to get the absolute value:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}

Solution 3 - Objective C

If you are curious as to what they are doing in the abs() function:

char abs(char i) {
    return -(i & 128) ^ i;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionredconservatoryView Question on Stackoverflow
Solution 1 - Objective CJonathan GrynspanView Answer on Stackoverflow
Solution 2 - Objective Cda Rocha PiresView Answer on Stackoverflow
Solution 3 - Objective CItzToxicView Answer on Stackoverflow