Keeping rotation values within a range of 0 to 360°

How can I keep the rotation values within a range of 0 to 360° no matter how many times I actually rotated an object? I need this as a value for a driver variable.

For example 945° => 225°.

• Thanks again, var - var // (2 * pi) * 2 * pi and var % (2 * pi both deliver a positive result, which is the positional equivalent to its negative. E.g. -980° => 100° (= -260°). Is there a way to get the precise negative result for negative values directly? I want to keep the sign (+/-) as directional information. – Jacquin Aug 6 at 10:42
• I've updated my answer, you probably want fmod – rjg Aug 6 at 11:28
• Grumble, nothing like a long comment on answer being deleted as you type. Mapping to (0, 2pi) expects a positive result. Keeping the sign would require mapping to (-2pi, 2pi) something like var % ((-2 if var < 0 else 2) * pi) There will be a big switch in value at the boundary. – batFINGER Aug 6 at 11:43

Modulo's partner in crime.

Alternatively to modulus could use its partner in crime div. a // (2 * pi) is how many integer multiples of 2pi the value is, eg if a = -3 * pi / 2 we get -1. If we subtract -1 multiples of 2pi from a we get pi / 2.

a - a // (2 * pi) * 2 * pi

You can use modulo x % 360.0, or x % (2 * pi) when operating in radians, which will wrap around to zero when the value x reaches a multiple of 360.0 or 2𝜋.

If you want signed results you can use fmod(x, 2*pi).

Beware of floating point inaccuracies when using the % operator.

• Thanks, I tried it as a scripted expression var%(2*pi) if var > 0 else var%(2*-pi) (var = rotation value in radians), which does what I want both for positive and negative rotation values. But the negative ones are not precisely calculated, so I get for -360° not 0° but -0.00001°? Is there a way to fix this? – Jacquin Aug 6 at 0:27
• Equivalent of fabs(var % (2 * pi)) – batFINGER Aug 6 at 1:19
• In hindsight the fabs is unnecessary For some reason abs isn't in the driver namespace. . @Jacquin When using modulo the result a % b is always sign of b. This explains the sign. Hence simply use var % (2 * pi) Please accept this answer. – batFINGER Aug 6 at 10:04