views:

343

answers:

3

I made this method

+ (CGFloat) round: (CGFloat)f {
    int a = f;
    CGFloat b = a;
    return b;
}

It works as expected but it only rounds down. And if it's a negative number it still rounds down.

This was just a quick method I made, it isn't very important that it rounds correctly, I just made it to round the camera's x and y values for my game.

Is this method okay? Is it fast? Or is there a better solution?

+1  A: 

A CGFloat is typedef'd to either a double or a float, so you can round them like any other real type:

CGFloat round(CGFloat aFloat)
{
    return (int)(aFloat + 0.5);
}

Other than that, yeah, your method works. Any good compiler will optimize it to the best it can.

zneak
+4  A: 

There are already standard functions with behaviors you might need in <math.h> such as: floorf, ceilf, roundf, rintf and nearbyintf (lasf 'f' means "float" version, versions without it are "double" versions).

It is better to use standard methods not only because they are standard, but because they work better in edge cases.

iPhone beginner
Ah, thank you,Assuming the iPhone is 32-bit it'd be best to use those float functions. :D
Johannes Jensen
+1  A: 

You are reinventing the wheel - and this is a C question, not Objective C. Just use the standard C round() function.

Paul Lynch