How to do decimal formatting in Objective-C?

Pretty new to the entire iPhone development scene. I'm just training, trying to create a basic calculator, I can add prime numbers, but I would like to support decimals.

Here is my code:

    - (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 is greatly appreciated.

+3
source share
1 answer

I think your format may be wrong. What result do you expect and what do you get?

If I guessed correctly, you can try the following:

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

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

EDIT: Avoid memory leak as pointed out in donkim comment!

+5
source

Source: https://habr.com/ru/post/1789365/


All Articles