I am trying to use a background worker which for each key in a dictionary save the contents to file. ACon is a personal class that calls a save function on the contents of a dictionary within it.
private void bwSaver_DoWork(object sender, DoWorkEventArgs e)
{
string[] Keys = ACon.GetKeys();
int num = 0;
foreach (string s in Keys)
{
ACon.Save(s);
int Len = Keys.Length;
double pctg = (num / Len);
//Below was by first attempt at getting the percentage. Above are my debugging attempts.
bwSaver.ReportProgress(num/Keys.Length*100);
num++;
}
}
I was hoping for it to report the progress by giving the key it is on / total keys * 100 for percentage but this wasn't working.
No matter what type I use for pctg; short, int, float, double, num/Len always = 0, yet if I switch it around, Len/num gives the correct value. Adding or removing brackets doesn't change anything. Am I just being silly and missing something or am I coding something wrong?
Here is some screenshots from VS2010 (Professional)
pctg as double:
pctg as float:
pctg as double, without brackets:
pctg with Len and num swapped:
Its not that you are changing the type for pctg, its based on the types of num and Len
Try:
float pctg = ((float)num / (float)Len);
If both num
and Len
are ints, then your code would do integer division, after which it would cast that integer to a float.
As mentioned by @CDspace below, the integer division will round to the nearest int, in your case, zero. Then casting zero to any other type is still zero.