1

我有一个应用程序,其中我有在 NSString 中以数千个值插入逗号的方法这个问题。

- (NSString *)formatStringF:(NSString *)string {
// Strip out the commas that may already be here:
NSString *newString = [string stringByReplacingOccurrencesOfString:@"," withString:@""];
if ([newString length] == 0) {
    return nil;
}

// Check for illegal characters
NSCharacterSet *disallowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
NSRange charRange = [newString rangeOfCharacterFromSet:disallowedCharacters];
if ( charRange.location != NSNotFound) {
    return nil;
}

// Split the string into the integer and decimal portions
NSArray *numberArray = [newString componentsSeparatedByString:@"."];
if ([numberArray count] > 2) {
    // There is more than one decimal point
    return nil;
}

// Get the integer
NSString *integer           = [numberArray objectAtIndex:0];
NSUInteger integerDigits    = [integer length];
if (integerDigits == 0) {
    return nil;
}


// Format the integer.
// You can do this by first converting to a number and then back to a string,
// but I would rather keep it as a string instead of doing the double conversion.
// If performance is critical, I would convert this to a C string to do the formatting.
NSMutableString *formattedString = [[NSMutableString alloc] init];
if (integerDigits < 4) {
    [formattedString appendString:integer];
} else {
    // integer is 4 or more digits
    NSUInteger startingDigits = integerDigits % 3;
    if (startingDigits == 0) {
        startingDigits = 3;
    }
    [formattedString setString:[integer substringToIndex:startingDigits]];
    for (NSUInteger index = startingDigits; index < integerDigits; index = index + 3) {
        [formattedString appendFormat:@",%@", [integer substringWithRange:NSMakeRange(index, 3)]];
    }
}

// Add the decimal portion if there
if ([numberArray count] == 2) {
    [formattedString appendString:@"."];
    NSString *decimal = [numberArray objectAtIndex:1];
    if ([decimal length] > 0) {
        [formattedString appendString:decimal];
    }
}






return formattedString;
 }
4

1 回答 1

3

为什么要重新发明轮子?只需使用NSNumberFormatter.

double someNumber = 1000.0;

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
// Use decimal style - this includes grouping
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
// Force two decimal places
[formatter setMinimumFractionDigits:2];
[formatter setMsximumFractionDigits:2];

NSString *formattedNumber = [formatter stringFromNumber:@(someNumber)];

这也有一个优点,它会根据用户的区域设置正确地格式化数字。

它将显示为 1,000.00 或 1.000,00 或 1 000,00 或其他适合用户的格式。

于 2013-08-21T04:25:40.753 回答