ToddB
ToddB

Reputation: 2520

objective-c check equality of float and int -- does 2.0000 == 2

Simple question, I know there must be a correct way to do this. I have a CGFloat that increases in increments of 1/16. I want to determine when this value becomes a whole number.

For lack of knowing the right way I am coming up with ideas like having another variable to keep track of the number of iterations and mod 16 it.

Upvotes: 1

Views: 558

Answers (3)

Paul R
Paul R

Reputation: 212979

It's better to do it the other way around, i.e. use an integer loop counter and convert this to a float:

for (int i = 0; i < 100; ++i)
{
    float x = (float)i / 16.0f;

    if (i % 16 == 0)
    {
        // if x is whole number...
    }
}

Upvotes: 2

Bartosz Ciechanowski
Bartosz Ciechanowski

Reputation: 10333

While you generally can't count on fractional floating point numbers to sum up to whole numbers, your case is exception to the rule since 1/16 is 2^(-4) and this number can be represented by float precisely:

- (void)testFloat
{
    float a = 0.0f;

    while (a != 2.0f) {
        a += 0.0625f;
    }

    NSLog(@"OK!");
}

Upvotes: 4

Ricky Stewart
Ricky Stewart

Reputation: 1152

Floating point arithmetic is inexact so you can't count on the value of your variable ever being exactly 2.0000.

"For lack of knowing the right way I am coming up with ideas like having another variable to keep track of the number of iterations andmod 16 it."

This is a wonderful idea.

Upvotes: 1

Related Questions