simple calculation not working for some reason

i checked the values while debugging and with FilesCompleted being 295 and TotalFilesCount being 25002 the returnvalue var is just 0, it should be 1 already.

No, because all the arithmetic is being done with integers. So first this expression is evaluated:

(FilesCompleted / TotalFilesCount)

That’s 295 / 25002. The result of that integer arithmetic is 0… and when you then multiply it by 100, you’ve still got 0. The simplest fix is just to do the multiplication first:

int returnvalue = (FilesCompleted * 100) / TotalFilesCount;

Note that that will overflow if FilesCompleted is greater than int.MaxValue / 100. You could fix that by either doing everything in floating point arithmetic:

int returnvalue = (int)((FilesCompleted * 100.0) / TotalFilesCount);

… or by using long integer arithmetic:

int returnvalue = (int)((FilesCompleted * 100L) / TotalFilesCount);

Neither of these are necessary if you don’t expect to have an insane number of files, of course. (You’re fine up to 42 million files…)

As a side note, your parameter names violate .NET naming conventions. They should be camelCased – totalFilesCount and filesCompleted.

Leave a Comment