Question

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#?

Was it helpful?

Solution

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 );

OTHER TIPS

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;
}

A longer alternative with Mod.

ItemCount = BrandCount / 4;
if (BrandCount%4 > 0) ItemCount++;

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top