# 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
``````

``````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);
``````
• ### How To Submit a iPhone App to the Appstore

by on July 5, 2012 - 0 Comments

The process to develop an iPhone app is not as hard as one might think. The entry into the app store has been opened up to many new types of develope...

• ### Develop iphone Apps on Windows

by on March 7, 2011 - 13 Comments

Top 10 Ways to Develop an iphone/ipad app without a Mac #1. Code in Java For Java developers, there is a workaround: XMLVM. XMLVM cross-compiles byte...

• ### Iphone Android App Ideas: Getting Started

by on March 19, 2011 - 3 Comments

Smartphone Application Ideas: Getting Started Smartphone application developers are constantly on the move. And since overzealous developers stick ...