Ben
Ben

Reputation: 4319

Percentage in LINQ comes out as zero

I have the following query. Why do I get zero as the value in the percent column?

var qPercentage = from q in qCounts
                          select new {
                              q.Category,
                              q.CategoryCouplet,
                              q.Subcategory,
                              Percent =  100*(q.Count / iTotal)
                          };

Counts has valid integer values, by the way!

Upvotes: 0

Views: 433

Answers (3)

Bala R
Bala R

Reputation: 108957

Try

Percent =  100*((float)q.Count / iTotal)

Upvotes: 0

xanatos
xanatos

Reputation: 111870

Because q.Count and iTotal are integer. You should do 100 * q.Count / iTotal.

Upvotes: 0

Jesper Larsen-Ledet
Jesper Larsen-Ledet

Reputation: 6723

It looks like you're doing integer division within the parenthesis. Try

100*(q.Count / (double)iTotal)

or if you want Percent to be an integer

(100 * q.Count) / iTotal

Upvotes: 4

Related Questions