Blog Archives

Use fmod for modulus calculations on floats

Everyone knows about the modulus operator (%) and that it returns the remainder of an integer division:

// mod = 1
int mod  = 11 % 2;

Occasionally you’ll need to get a remainder of a floating point calculation. I’m finding this more and more while using CoreAnimation and CoreGraphics since screen placement is handled through CGFloats. Fortunately the math.h library includes the function fmod to handle this:

#import <math.h>

CGFloat mod = fmod(47.236456, 5);
NSLog(@"%f", mod);
// prints 2.236456

While your CGRects and CGPoints will be whole numbers most of the time, when dealing with animations coordinates will often have trailing decimals. Additionally you’ll find that points on retina display interfaces will frequently be measured to the half pixel.

fmod reference on cplusplus.com