Reputation: 28624
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#?
Upvotes: 9
Views: 14122
Reputation: 114825
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;
}
Upvotes: 12
Reputation: 37858
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.
Upvotes: 2
Reputation: 7856
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 );
Upvotes: 22
Reputation: 3963
A longer alternative with Mod.
ItemCount = BrandCount / 4;
if (BrandCount%4 > 0) ItemCount++;
Upvotes: 7