JKennedy
JKennedy

Reputation: 18799

Calculating Integer Percentage

So I would like to calculate the percentage progress of my program as the nearest integer value

In my examples lets take

int FilesProcessed = 42;
int TotalFilesToProcess = 153;

So First I tried:

Int TotalProgress = ((FilesProcessed / TotalFilesToProcess) * 100)

This returned TotalProgress = 0

Then I tried

Int TotalProgress = (int)((FilesProcessed / TotalFilesToProcess) * 100)

This gives compiler error saying Cannot implicitly convert type decimal to int

Ive tried

Int TotalProgress = Math.Round((FilesProcessed / TotalFilesToProcess) * 100)

and get The call is ambiguous between decimal and double

and so now I've come here for help?

Upvotes: 14

Views: 33245

Answers (3)

Daniel Silva
Daniel Silva

Reputation: 837

If you want to be more accuracy, you can use:

int TotalProgress = Convert.ToInt32(Math.Round(((decimal)FilesProcessed / TotalFilesToProcess) * 100, 0));

If the numbers are greater you will have a difference. For example

int FilesProcessed = 42;
int TotalFilesToProcess = 1530;

The result with decimals will be: 2.74%, if you use the previous methods, you would find 2%, with the formula I am proposing you will obtain 3%. The last option has more accuracy.

Upvotes: 3

Max Brodin
Max Brodin

Reputation: 3938

int FilesProcessed = 42;
int TotalFilesToProcess = 153;
int TotalProgress = FilesProcessed * 100 / TotalFilesToProcess;

Console.WriteLine(TotalProgress);

https://dotnetfiddle.net/3GNlVd

Upvotes: 12

ken2k
ken2k

Reputation: 48975

Cast to double first so it doesn't compute a division between integers:

int totalProgress = (int)((double)FilesProcessed / TotalFilesToProcess * 100);

Upvotes: 35

Related Questions