如何在Objective-C中进行十进制格式?

时间:2023-01-18 19:54:33

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.

对整个iPhone开发领域来说都是全新的。我只是在练习,尝试创建一个基本的计算器,我可以添加简单的数字,但是我想支持小数点。

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.

感谢任何帮助。

1 个解决方案

#1


5  

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.

其中5表示总位数(以填充对齐方式表示),2表示小数点后两位。

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

编辑:避免内存泄漏,正如donkim在评论中提到的!

#1


5  

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.

其中5表示总位数(以填充对齐方式表示),2表示小数点后两位。

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

编辑:避免内存泄漏,正如donkim在评论中提到的!