gpt4 book ai didi

objective-c - 如何以这种格式显示数字?

转载 作者:行者123 更新时间:2023-11-29 04:45:18 26 4
gpt4 key购买 nike

我正在文本字段中显示一个数字。它将数字显示为“1234”,但如果我输入另一个显示为“12345”的大数字,我想将其显示为“1,234”的格式,但如果我输入 123456,我想将其显示为“12,345”显示为“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);

关于objective-c - 如何以这种格式显示数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9750005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com