2011-07-11 60 views
1
label.text = [NSString stringWithFormat:@"%.2f",final]; 

上述語句顯示小數點後兩位數字的變量「final」中可用的浮點值。自定義小數點浮點數

我想在這取決於我已經給一個整數變量這樣

label.text = [NSString stringWithFormat:@"%.if",j,final] 

這裏j中的數目,以顯示小數點後的位數是整數變量。不管我爲j輸入多少個小數,它都應該顯示。我需要適當的語法來顯示上述語句。

+0

說清楚。你想要什麼輸出。什麼是J值?什麼是最終價值?和你想要的輸出。 –

回答

0

我不知道是否有一個一行,將你想要做什麼,但你總是可以做:

NSString* formatString = [NSString stringWithFormat: @"%%.%if", j]; 
label.text = [NSString stringWithFormat:formatString, final]; 
+0

謝謝你的所有 – Uday

2

NSNumberFormatter有你想要做什麼的能力。在格式化字符串之前,可以使用變量設置以下任何方法。

- (void)setMinimumIntegerDigits:(NSUInteger)number 
- (void)setMinimumFractionDigits:(NSUInteger)number 
- (void)setMaximumIntegerDigits:(NSUInteger)number 
- (void)setMaximumFractionDigits:(NSUInteger)number 

Data Formatting Guide - Number Formatters

0

可以使用NSNumberFormatter

NSNumberFormatter *nf = [[NSNumberFormatter alloc] init]; 
[nf setFormatterBehavior:NSNumberFormatterBehaviorDefault]; 
[nf setNumberStyle:NSNumberFormatterDecimalStyle]; 
[nf setMaximumFractionDigits:j]; // Set the number of decimal places here 

label.text = [nf stringFromNumber:[NSNumber numberWithFloat:final]]; 

[nf release]; 
4

IEEE printf specApple follows狀態:

場寬度,或精度,或二者,可以是用星號0表示('*')。在這種情況下,類型爲int的參數提供了字段寬度 或精度。

這意味着

label.text = [NSString stringWithFormat:@"%.*f",j,final] 

可能的工作,但我有沒有可用的,現在來測試它的平臺。

+0

+1!哇!大! – EmptyStack

+0

+1好的答案! – Joe

+0

+1我從來不知道你以前可以爲此做好準備。 – JeremyP