我在文本字段中显示一个数字。其中显示数字为“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