2012-06-02 40 views
0

好吧,我試圖讓我的值用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,但是值並沒有改變。

我在做什麼錯?

回答

1

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; 
} 
+0

是的工作!謝謝。但還有一個問題,我如何在不考慮整個NumberFormatter路由的情況下將$符號放在我的值前面? (例如1.88 - > $ 1.88) – iamruskie

+0

正如Kurt Revis上面所建議的那樣,使用stringWithFormat這是一個非常強大的工具。只需將您的美元符號插入字符串中,如「$%1.0f」。 –

2

ceilf不會修改您傳入的值。它返回修改後的值。

floatRoundValue = ceilf(floatRoundValue); 
+0

沒關係啊,這是有道理的。謝謝。我太親密了哈哈 – iamruskie

+0

另外,我怎麼會在我的價值觀前面放一個$符號? (例1.88 - > $ 1.88) – iamruskie

+0

將'$'放在格式字符串中。查看' - [NSString stringWithFormat:]'的文檔以瞭解它是如何工作的。 –

1

如果您需要之前有一個$符號:

-(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