如何以这种格式显示数字?
我在文本字段中显示一个数字。其中显示数字为“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;
}
你可以这样说:
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);
它没有给出想要的结果..仍然显示为12345没有得到逗号作为分隔符。我认为我们必须添加一些字符串分隔符 – Karthikeya 2012-03-17 13:26:01
@Karthikeya - 这很奇怪,你可以发布你的更新代码吗? – sch 2012-03-17 13:39:30
你可以检查我的编辑。 – Karthikeya 2012-03-17 13:41:13
首先,通读NSNumberFormatter reference page上的方法列表。完成之后,您可能会意识到需要使用-setHasThousandSeparators:
方法打开千位分隔符功能。您也可以使用-setThousandSeparator:
方法设置自定义分隔符,尽管您可能不需要这样做。
谢谢你,但这两种方法不被Xcode识别.... – Karthikeya 2012-03-17 14:35:27
请参阅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