【问题标题】:How to round a float value with button如何使用按钮舍入浮点值
【发布时间】:2012-06-07 15:10:24
【问题描述】:

好的,所以我正在尝试使用 IBAction 将我的值四舍五入到最接近的整数。

So 1.88 -> 2.00 ,  
11.40 -> 12.00 ,   
111.01 -> 112.00, etc.    

-

-(IBAction)roundUp:(id)sender   
{   
    float floatRoundValue=lblTotalRound.text floatValue];
    ceilf(floatRoundValue);
    NSString *stringRoundValue = [NSString stringWithFormat:@"%1.0f", floatRoundValue];
    lblTotalRound.text=stringRoundValue;
}

这就是我得到的。但它仍然向下舍入到 0.5 以下并到最接近的整数

(Ex. 1.19 -> 1 , i need 1.19 -> 2.00). 

我已经尝试了 %1.2f,但值根本没有改变。

我做错了什么?

【问题讨论】:

    标签: iphone xcode cocoa xcode4


    【解决方案1】:

    ceilf 不会修改您传入的值。它返回一个修改后的值。

    floatRoundValue = ceilf(floatRoundValue);
    

    【讨论】:

    • 啊,好吧,有道理。谢谢。我是如此接近哈哈
    • 另外,我如何在我的值前面加上一个 $ 符号? (例如 1.88 -> 1.88 美元)
    • 将$ 放入格式字符串中。查看-[NSString stringWithFormat:] 的文档以了解其工作原理。
    【解决方案2】:

    ceilf 是一个返回值的函数 (https://developer.apple.com/library/mac/#documentation/Darwin/Reference/Manpages/man3/ceil.3.html),您只需要更改它到下面一行。

    floatRoundValue = ceilf(floatRoundValue);
    

    所以在你的情况下,完整的代码应该是这样的。

    -(IBAction)roundUp:(id)sender   
    {   
        float floatRoundValue=lblTotalRound.text floatValue];
        floatRoundValue = ceilf(floatRoundValue);
        NSString *stringRoundValue = [NSString stringWithFormat:@"%1.0f", floatRoundValue];
        lblTotalRound.text=stringRoundValue;
    }
    

    【讨论】:

    • 是的,行得通!谢谢。但是还有一个问题,我如何在不走整个 NumberFormatter 路线的情况下在我的值前面加上一个 $ 符号? (例如 1.88 -> 1.88 美元)
    • 正如 Kurt Revis 上面建议的那样,使用 stringWithFormat 这是一个非常强大的工具。只需将美元符号插入到字符串中,例如“$%1.0f”。
    【解决方案3】:

    如果你需要在前面加一个$符号:

    -(IBAction)roundUp:(id)sender   
    {   
        float floatRoundValue=(lblTotalRound.text floatValue]; 
        floatRoundValue = ceilf(floatRoundValue);
        NSString *stringRoundValue = [NSString stringWithFormat:@"$%1.0f", floatRoundValue];
        lblTotalRound.text=stringRoundValue;
    }
    

    NSString Class Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多