3

当他们在我的应用程序中点击计算按钮时,我正在执行以下代码:

float sqft = ([textfield1.text floatValue]);
    float thick= ([textfield2.text floatValue]);
    float cos = ([textfield3.text floatValue]);
    float eff = ([textfield4.text floatValue]);

    float num = ((thick*.5)*sqft)/eff;
    float cost = (num*cos);
    float costft = (cost/sqft);

    label1.text = [NSString stringWithFormat:@"%2.f",num];
    label2.text = [NSString stringWithFormat:@"%2.f",cost];
    label3.text = [NSString stringWithFormat:@"%2.f",costft];

当我这样做时,标签只返回零。我已将标签设置为字符串,只是为了看看它是否是一个委托,但我不知道为什么我的公式只返回零

4

3 回答 3

3

问题在于您在代码中使用 %2.f 的方式,

%2.f 以 2 数字格式为您提供答案的四舍五入值。如果您的任何答案小于或等于 0.5 。然后你得到 0 作为答案。

现在它应该可以工作了

float sqft = ([textfield1.text floatValue]);
float thick= ([textfield2.text floatValue]);
float cos = ([textfield3.text floatValue]);
float eff = ([textfield4.text floatValue]);

float num = ((thick*.5)*sqft)/eff;
float cost = (num*cos);
float costft = (cost/sqft);

label1.text = [NSString stringWithFormat:@"%2f",num];
label2.text = [NSString stringWithFormat:@"%2f",cost];
label3.text = [NSString stringWithFormat:@"%2f",costft];
于 2013-05-04T05:25:34.890 回答
3

它在我的最后工作正常。但在一种情况下,ZERO当您的价值为 0.786676 时,您将获得价值。

    textfield1.text = @"123.89";
    textfield2.text= @"123.00";
    textfield3.text= @"123.7";
    textfield4.text= @"123";


    float sqft = ([textfield1.text floatValue]);
    float thick= ([textfield2.text floatValue]);
    float cos = ([textfield3.text floatValue]);
    float eff = ([textfield4.text floatValue]);

    float num = ((thick*.5)*sqft)/eff;
    float cost = (num*cos);
    float costft = (cost/sqft);

    NSLog(@"Num : %@",[NSString stringWithFormat:@"%2.f",num]);
    NSLog(@"Cost : %@",[NSString stringWithFormat:@"%2.f",cost]);
    NSLog(@"Costft :  %@",[NSString stringWithFormat:@"%2.f",costft]);

输出

数量 : 62 成本 : 7663 成本 : 62

于 2013-05-04T05:38:11.227 回答
1

You want to limit the digits after the decimal point to two - that is why you are using .2f, right? If so, you should use this @"%.2f"

Just try this:

label1.text = [NSString stringWithFormat:@"%.2f",num];  
label2.text = [NSString stringWithFormat:@"%.2f",cost];  
label3.text = [NSString stringWithFormat:@"%.2f",costft];
于 2013-05-04T05:51:40.043 回答