Nicholas Gibson
Nicholas Gibson

Reputation: 208

Addition between Label and Textfield

I am trying to add the value of my textfield plus the value of my label and place it in another label.

-(IBAction)finalTipTotalSelection:(id)sender
{
    NSString *billFinalAmount = [billAmountTextField text];

    float billFinalAmountFloat = [billFinalAmount floatValue];

    NSString *tipTotalAmount = [resultLabel text];

    float tipTotalAmountFloat = [tipTotalAmount floatValue];

    float finalAmountShow = billFinalAmountFloat + tipTotalAmountFloat;

    NSString *finalResult = [NSString stringWithFormat:@"$ %0.2f", finalAmountShow];

    [finalTotalLabel setText:finalResult];
}

I am creating floatValues for the Strings and then in a float adding the other floatValues together, and finally displaying it in a label. The only issues is when I run this code the finalTotalLabel (shows the final amount) only shows the value of the billAmountTextField. So if the billAmountTextField = 187.82 and the tipTotalAmount was 10, the finalTotalLabel would show 187.82 (not 197.82). I cant seem to find my mistake. Thanks for your help!

Upvotes: 0

Views: 51

Answers (1)

Valent Richie
Valent Richie

Reputation: 5226

It is caused by the tipTotalAmount having the $ character at the beginning of the string. The resulting float value for the tip amount will be 0.0 because:

floatValue... returns 0.0 if the receiver doesn’t begin with a valid text representation of a floating-point number.

You can take a look at the class reference of NSString for the explanation of the return value of floatValue.

Try to filter out the non decimal and dot character first from the NSString instance before passing the message floatValue to it, for example:

NSMutableCharacterSet *_alnum = [NSMutableCharacterSet characterSetWithCharactersInString:@"."];
[_alnum formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
NSString *newTipTotalAmount = [[tipTotalAmount componentsSeparatedByCharactersInSet:
                            [_alnum invertedSet]]
                           componentsJoinedByString:@""];
float tipTotalAmountFloat = [newTipTotalAmount floatValue];

Here the newTipTotalAmount will be "39.19" compared to the tipTotalAmount which is "$ 39.19" and passing the floatValue message to newTipTotalAmount will give you the correct float value.

Upvotes: 1

Related Questions