Pétur Ingi Egilsson
Pétur Ingi Egilsson

Reputation: 4442

How to prevent division by zero when the denominator is a CGFloat?

I have a number which is a CGFloat and I want to divide it by some number. How can I make sure that the divisor is not equal to zero or NaN?

Upvotes: 0

Views: 719

Answers (2)

Wyetro
Wyetro

Reputation: 8578

Do something like this:

CGFloat number = 5 //declare the CGFloat
CGFloat divisor = 2 //where this equals whatever you want to divide by

if (divisor != 0 && !(isnan(divisor))){
 CGFloat answer = number / divisor;
}

Upvotes: 0

s1m0n
s1m0n

Reputation: 7685

The following example checks the divisor before the division to make sure it's not 0 or NaN.

CGFloat dividend = 5.f;
CGFloat divisor = 3.f;

if (! (isnan(divisor) || divisor == 0.f)){
    CGFloat quotient = dividend / divisor;
}

Upvotes: 1

Related Questions