2012-03-17 59 views
0

我在文本字段中顯示一個數字。其中顯示數字爲「1234」,但如果我輸入顯示爲「12345」的另一個大數字,但我想將其顯示爲「12,345」,如果我輸入的123456必須以顯示爲「123,456」。如何以期望的格式格式化此號碼?如何以這種格式顯示數字?

-(void)clickDigit:(id)sender 
{ 
    NSString * str = (NSString *)[sender currentTitle]; 
    NSLog(@"%@",currentVal); 


    if([str isEqualToString:@"."]&& !([currentVal rangeOfString:@"."].location == NSNotFound)) 
    { 
     return; 
    } 
    if ([display.text isEqualToString:@"0"]) 
    { 

     currentVal = str; 
     [display setText:currentVal]; 
    } 

    else if([currentVal isEqualToString:@"0"]) 
    { 
     currentVal=str; 
     [display setText:currentVal]; 

    } 
    else 
    { 
     if ([display.text length] <= MAXLENGTH) 
     { 
      currentVal = [currentVal stringByAppendingString:str]; 
      NSLog(@"%@",currentVal); 
      [display setText:currentVal]; 
     } 
     currentVal=display.text; 
    } 
} 

這是我用來在文本字段中顯示數字的代碼。


編輯:我改變了我的代碼爲以下,但仍然沒有得到正確格式化的數字:

if ([display.text length] <= MAXLENGTH) { 
    currentVal = [currentVal stringByAppendingString:str]; 
    NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init]; 
    [myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
    NSNumber *tempNum = [myNumFormatter numberFromString:currentVal]; 
    NSLog(@"My number is %@",tempNum); 
    [display setText:[tempNum stringValue]]; 
    currentVal=display.text; 
} 
+0

請參閱http://stackoverflow.com/questions/5406366/formatting-a-number-to-show-commas-and-or-dollar-sign-接受的答案http://stackoverflow.com/a/5407103/928098看起來像會解決你的問題 – 2012-03-17 12:42:31

+0

我認爲OP不需要顯示字符串中的美元符號,就像你鏈接到的答案一樣。 – sch 2012-03-17 13:03:18

回答

1

你可以這樣說:

int myInt = 12345; 
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
formatter.numberStyle = NSNumberFormatterDecimalStyle; 
NSNumber *number = [NSNumber numberWithInt:myInt]; 
NSLog(@"%@", [formatter stringFromNumber:number]); // 12,345 

編輯

您沒有正確實施此項,關鍵是要使用[formatter stringFromNumber:number]獲取數字的字符串表示形式,但您沒有這樣做。因此,將您的代碼更改爲:

currentVal = [currentVal stringByAppendingString:str]; 
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init]; 
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
NSNumber *tempNum = [myNumFormatter numberFromString:currentVal]; 
NSLog(@"My number is %@",tempNum); 
[display setText:[myNumFormatter stringFromNumber:tempNum]]; // Change this line 
currentVal=display.text; 
NSLog(@"My formatted number is %@", currentVal); 
+0

它沒有給出想要的結果..仍然顯示爲12345沒有得到逗號作爲分隔符。我認爲我們必須添加一些字符串分隔符 – Karthikeya 2012-03-17 13:26:01

+0

@Karthikeya - 這很奇怪,你可以發佈你的更新代碼嗎? – sch 2012-03-17 13:39:30

+0

你可以檢查我的編輯。 – Karthikeya 2012-03-17 13:41:13

0

首先,通讀NSNumberFormatter reference page上的方法列表。完成之後,您可能會意識到需要使用-setHasThousandSeparators:方法打開千位分隔符功能。您也可以使用-setThousandSeparator:方法設置自定義分隔符,儘管您可能不需要這樣做。

+0

謝謝你,但這兩種方法不被Xcode識別.... – Karthikeya 2012-03-17 14:35:27