views:

2058

answers:

4
+3  Q: 

Integer math in c#

I have a menu of product brands that I want to split over 4 columns. So if I have 39 brands, then I want the maximum item count for each column to be 10 (with a single gap in the last column. Here's how I'm calculating the item count for a column (using C#):

int ItemCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(BrandCount) / 4m));

All that conversion seems really ugly to me. Is there a better way to do math on integers in C#?

+5  A: 

A longer alternative with Mod.

ItemCount = BrandCount / 4;
if (BrandCount%4 > 0) ItemCount++;
GavinCattell
Longer? Simpler! +1
Treb
+15  A: 

You can cast:

int ItemCount = (int) Math.Ceiling( (decimal)BrandCount / 4m );

Also, because int/decimal results in a decimal you can remove one of the casts:

int ItemCount = (int) Math.Ceiling( BrandCount / 4m );
David Kemp
This was what I was about to write. +1.
OregonGhost
It is what I wound up writing. :) +1 as well.
John Rudy
Wow, that is so much cleaner. Thanks.
Ben Mills
+2  A: 

Perhaps try something like this ... Assuming BrandCount is an integer. You still have the same casts, but it might be clearer:

int ItemCount = (int)(Math.Ceiling(BrandCount / 4m));

I'm not a huge fan of the Convert class, and I avoid it whenever possible. It always seems to make my code illegible.

John Rudy
I totally agree with you -> Convert.ToInt32(foo) is ugly compared to (int)foo.
David Kemp
So does the cast do exactly the same thing as the Convert?
Ben Mills
@Ben Mills: In this case, yes (converting numbers). In general, no.
OregonGhost
+4  A: 

Why are you even using a decimal?

int ItemCount = (BrandCount+3)/4;

The +3 makes sure you round up rather than down:

(37+3)/4 == 40/4 == 10
(38+3)/4 == 41/4 == 10
(39+3)/4 == 42/4 == 10
(40+3)/4 == 43/4 == 10

In general:

public uint DivUp(uint num, uint denom)
{
    return (num + denom - 1) / denom;
}
Motti
I like the trick, but I think it's harder to see the purpose of the code. The answer I accepted is easy to come back and maintain.
Ben Mills
You call *this* a trick? I don't envy you trying to maintain any but the most trivial of programs...
Motti
seriously — ceil(a/b)=((a+b-1)/b) is a "trick" programmers have been using for years before C#.
cce