Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

taking absolute value of CGFloat

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

like image 274
adit Avatar asked Jan 16 '13 01:01

adit


People also ask

How do I return an absolute value in Swift?

Swift Double abs() The abs() method returns the absolute value of the given value.

How do I change a negative number to a positive in Swift?

The abs() function returns the absolute value of a number, which is a way of describing how far away from zero it is without thinking about whether it's positive or negative. It's most commonly used if you have a number that you need to be positive, because whether you pass 30 or -30 to abs() you get back 30.

What is abs in Swift IOS?

Returns the absolute value of the given number.

What is fabs in Swift?

Returns the absolute value of each element in a vector.


1 Answers

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.

like image 164
bluefloyd8 Avatar answered Sep 29 '22 01:09

bluefloyd8