How to prorate in discrete blocks

Recently, I had the occasion to contemplate prorating logic. Alright, fine, I was tasked with implementing some business logic which required prorating, but in discrete blocks. Let me explain.

Suppose you’re providing a service, and you charge in minutes. Say as a promotion, you give away 600 minutes for free per month, on condition that the customer stay with you for a certain number of months. The customer backs out on that condition on the 17th of his first month, so the customer has to pay for the rest of the free minutes of that month (there are 31 days for that month). BUT, and here’s the kicker, the price must be calculated based on blocks of 6 minutes.

So you have to prorate the remaining minutes, and it has to be in multiples of 6.

Ok, that wasn’t much of a challenge. I thought I’d just write down how to do it anyway. Here’s the C# code.

int num = (31 - 17), den = 31, block = 6, total = 600;
int prorated = 0;
prorated = (int)(Math.Round(((double)num / den) / block * total, 0)) * block;

The only things to note are the casts to int and double. And that the example was quite contrived.