Skene
Skene

Reputation: 53

How do I do decimal formatting in Objective-C?

Pretty new to the whole iPhone development scene. I am just practicing, trying to create a basic calculator, I can add simple numbers but I'd like to support decimal places.

Heres my code so far:

    - (IBAction) calculate
{
    double number1 = ([textField.text doubleValue]);
    double answer = number1+([textField2.text doubleValue]);
    label.text = [[NSString alloc] initWithFormat:@"%2.f", answer];

}

- (IBAction) clear
{
        textField.text = @"";
        textField2.text = @"";
        label.text = @"";

}

Any help much appreciated.

Upvotes: 3

Views: 5090

Answers (1)

Dave
Dave

Reputation: 3448

I think your format might be wrong. What is the output you're expecting, and what are you getting?

If I'm guessing correctly, you may want to try this:

label.text = [NSString stringWithFormat:@"%5.2f", answer];

where the 5 means total digits (in terms of padding for alignment), and the 2 means 2 decimal places.

EDIT: avoiding memory leak, as mentioned in donkim's comment!

Upvotes: 5

Related Questions