taking absolute value of CGFloat

| | August 8, 2015

How can I do that? I tried the abs() but it only works for int’s. Is there a built in way to do so?

CGFloat flo = -123;
abs(flo)

this returns 0

4 Responses to “taking absolute value of CGFloat”

  1. Use fabs()

    CGFloat f = -123.4f;
    CGFloat g = fabs(f);
    

    CGFloat is defined as a double on 64-bit machines, and float on 32-bit machines. If you are targeting both 64 and 32 bit than this answer gets more complicated, but is still correct.

    You want to use fabs() because it works on double datatypes which are larger than float. On 32-bit, assigning the return value of fabs() (which is a double) into a CGFloat (which is a float) is ok ONLY if you are taking the absolute value of a CGFloat or float. You would potentially overflow a 32-bit CGFloat if you try to store the absolute value of a large double number. In short, 64-bit is fine, and on 32-bit don’t mix and match double and CGFloat and you’ll be fine.

    The ABS() macro apparently can have side-effects on some compilers.

  2. I normally just use the ABS macro, as far as I can tell, it works regardless of which system you’re on or which primitive you’re using.

    CGFloat x = -1.1;
    double y = -2.1;
    NSInteger z = -5;
    
    x = ABS(x);
    y = ABS(y);
    z = ABS(z);
    
  3. For 64/32 bit system

    #if CGFLOAT_IS_DOUBLE
        CGFloat g = fabs(flo);
    #else
        CGFloat g = fabsf(flo);
    #endif
    
  4. Small addition:

    CGFloat g = fabs(f);
    

    This will result in a casting warning, because fabs() returns a double value.
    To get a float value back, you need to use fabsf().

    CGFloat g = fabsf(f);
    

Leave a Reply