Search code examples
iphoneobjective-cxcodeuislidernumber-formatting

Help with UISlider


With my UISlider, if my value 'tipPercentage' gets to 10 or more, the label 'costWithTipLabel' gets set back to the textField's 'costWithoutTip' value starting with a 10% tip increase.

I would really appreciate it if you could take a look at my code and let me know of the problem causing this.

Thanks in advanced.

- (IBAction)aSliderChanged:(id)sender {
    UISlider *slider = (UISlider *)sender;
    if (slider == tipslide) {
        NSString *tip = [NSString stringWithFormat:@"%.f", slider.value * 100];
        float tipPercentage = [tip floatValue];
        NSString *multiplier = [NSString stringWithFormat:@"1.%.f", tipPercentage];
        [costWithTipLabel setText:[NSString stringWithFormat:@"%.2f", [[costWithoutTip text] floatValue] * [multiplier floatValue]]];
        [tipTextLabel setText:[[NSString stringWithFormat:@"Tip (%.f", slider.value *100]stringByAppendingString:@"%):"]];
    }
    else if (slider == peopleslide) {
        NSString *p = [NSString stringWithFormat:@"%.f", slider.value*10];
        float numOfPeople = [p floatValue];
        [numberOfPeopleTextLabel setText:[NSString stringWithFormat:@"Each (%.f):", numOfPeople]];
        [numberOfPeopleLabel setText:[NSString stringWithFormat:@"%.2f", [[costWithTipLabel text] floatValue]/numOfPeople]];
    }
    [totalBillCost setText:[NSString stringWithFormat:@"%.2f", [[costWithTipLabel text] floatValue]]];
}

Solution

  • I expect it has to do with unexpected formatting of your strings. I suggest you break your stringWithFormat assignments into multiple simple (non-nested) statements, and then NSLog your values using as generic a format (%f) as possible. Then you should be able to track down where the problem is.