- Home /
Is there a modulus operator in Unity JavaScript?
is there a mod operator? example c = b%a or c = b mod a e.g., 5%2 = 1
Answer by spinaljack · Aug 21, 2010 at 10:12 PM
Yes,
if(Time.frameCount%10 == 0)
returns true every 10 frames
Sweet. Thanks. I was using it with = overloaded i.e., %=, and got an error.
You may have the value you want from this, but this is incorrect. The % operator means remainder. If you use this with a negative value, you will have strange results.
Answer by InoGamalinda · Aug 10, 2013 at 03:55 PM
The % operator is the Remainder operator Example:
% 3 -> 0
% 3 -> -2
% 3 -> -1
0 % 3 -> 0
1 % 3 -> 1
2 % 3 -> 2
3 % 3 -> 0
To do a real Modulo, you need to make or find a function similar to this:
function modulo(dividend : int, divisor : int) : int {
return (((dividend) % divisor) + divisor) % divisor;
}
Results:
% 3 -> 0
% 3 -> 1
% 3 -> 2
0 % 3 -> 0
1 % 3 -> 1
2 % 3 -> 2
3 % 3 -> 0
Notice you get the same 0, 1, 2 cycle even when you reach the negative numbers. With this, you can get a consistent indexing for say like enumerators or arrays.
Note: This assumption is from Google calculator's -2 % 3 = 1 in contrast with JavaScripts -2 % 3 = -2.
This is by far and away the best answer and gets over javascripts idea that a negative remainder can exist!!!
Answer by photon · Aug 27, 2010 at 08:30 AM
If you are looking for a math function though, just use Javascripts %-operator.
Meaning, if you want to calculate number mod 2 use number%2
The value of this operation is the division remainder (9%2 = 1)
Answer by Dansl · Sep 30, 2010 at 09:07 PM
You can. Just Do (a = a % b) because (a %= b) does not work...
Your answer
Follow this Question
Related Questions
How do use the % operator? 2 Answers
Overload Operator in UnityScript? 0 Answers
Setting Scroll View Width GUILayout 1 Answer
Javascript And operator not working 1 Answer
+= operator doesn't work (Javascript) 4 Answers