我在文本字段中顯示一個數字。其中顯示數字爲「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;
}
請參閱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
我認爲OP不需要顯示字符串中的美元符號,就像你鏈接到的答案一樣。 – sch 2012-03-17 13:03:18