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
Swift Double abs() The abs() method returns the absolute value of the given value.
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.
Returns the absolute value of the given number.
Returns the absolute value of each element in a vector.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With