Search code examples
iosobjective-cios6nslog

Adding fractions calculation not working in IOS


I am trying to add fractions to get a value to put in for my progress bar but am just getting 0. here is what I have and what it is logging.

 NSLog(@"prog::%f",self.progView.progress);
    int total = self.forms.count;
   float calc =  (float)(self.progView.progress / total) + (1/total);
    NSLog(@"calc::%f",calc);
    NSLog(@"total::%d",total);
    self.progView.progress = calc;
    NSLog(@"prog now:%f", self.progView.progress);

Log:

prog::0.000000
calc::0.000000
total::4
prog now:0.000000

Solution

  • Take care of where you place your cast to float. Try changing from this:

    float calc =  (float)(self.progView.progress / total) + (1/total);
    

    To this:

    float calc =  ((float)self.progView.progress / (float)total) + (1/(float)total);
    

    Alternatively, make total a float rather than an int, e.g.

    float total = self.forms.count;
    float calc =  ((float)self.progView.progress / total) + (1 / total);