Amazing that I’ve been programming in Java for about 15 years, and I hadn’t run into this before. Tells you just how insidious this could be. Java’s ‘%’ operator acts like a modulo operator most of the time, but it’s a remainder operator. Your formula may work just fine in C, Python, Perl, Excel, and everywhere else— until you hit a negative number.

The difference is that the range of modulo-n is 0..(n-1) for positive n, whereas the range of Java’s quasi-modulo is -(n-1)…(n-1). So x%3 in Java goes from -2 to 2, whereas everywhere else it goes from 0 to 2. If you get a negative result, you need to add 3 to get the right answer.

This comes up because I’m trying to find the quarter that a month is in. Quarters can be defined as starting in any month (e.g. the fiscal year for my church starts in July, so Q1 is July, August, and September.) But since months are a cycle of 12 (a modulo-12 number system), there are only three kinds of quarter systems: January starts a quarter, February starts a quarter, and March starts a quarter. Call them 0, 1, and 2, and call the months 0-11 (the way Java painfully does), and you can find the number of months since the start of the quarter as (month-quarterOffset)%3. As long as you’re not using Java.

### Like this:

Like Loading...

*Related*