# make numbers wrap around

## Recommended Posts

Sync Views    139
How can I make a double or int wrap around between 0 <= x < 360 So x would go to y
x     -> y
-90   -> 270
360   -> 0
-180  -> 180
-45   -> 315
etc

I know I can do it by a loop but is there a better way for wrapping numbers around?
double WrapDeg(double Dir)
{
while(Dir <  0)   Dir += 360;
while(Dir >= 360) Dir -= 360;
return Dir;
}


##### Share on other sites
fpsgamer    856
Quote:
 Original post by Sync ViewsHow can I make a double or int wrap around between 0 <= x < 360

Assuming C++...

#include <cmath>
...
double wrappedValue = fmod (value,360.0); // modulo for real (eg. float or double) values

##### Share on other sites
blueapple    162
Instead of using loops, you could use the modulus operator (%):
int angle = 725;angle = angle % 360; // angle is now 25angle = angle % 360; // angle is still 25

##### Share on other sites
fpsgamer    856
Quote:
 Original post by blueappleInstead of using loops, you could use the modulus operator (%):int angle = 725;angle = angle % 360; // angle is now 25angle = angle % 360; // angle is still 25

That won't work.

The modulo operator only works for integral types. The OP specified he is using doubles. Use fmod() for real (eg. floating point) valued types.

##### Share on other sites
blueapple    162
Quote:
 Original post by Sync ViewsHow can I make a double or int wrap around between 0 <= x < 360

But you're right, for doubles, it won't work (and I'm not sure about negative numbers).

##### Share on other sites
fpsgamer    856
Quote:
Original post by blueapple
Quote:
 Original post by Sync ViewsHow can I make a double or int wrap around between 0 <= x < 360

But you're right, for doubles, it won't work (and I'm not sure about negative numbers).

##### Share on other sites
thre3dee    100
Quote:
 Original post by blueappleInstead of using loops, you could use the modulus operator (%):int angle = 725;angle = angle % 360; // angle is now 25angle = angle % 360; // angle is still 25

Actually the angle is 5º (2×360º=720º)