1

I have an application that needs to display metric units in millimeters and based on the research that I have done (e.g. http://physics.nist.gov/cuu/pdf/sp811.pdf), it is recommended that you don't add grouping separators until you have 5 digits. Is this possible with NSNumberFormatter? I know I could test the value and enable/disable grouping based on its size but I would rather use the appropriate configuration for the NSNumberFormatter if it exists. (BTW, I am on Mac OS X) So for example:

3456 should be shown as 3456 mm

10234 should be shown as 10,234 mm (assuming comma is the grouping separator)

I have read the Apple docs and didn't see anything. I experimented with different searches to find the answer on Stackoverflow but couldn't find a similar question.

Here is how I am currently setting up my NSNumberFormatter:

if (numberFormatter == nil) {
    numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [numberFormatter setLocale:[NSLocale currentLocale]];
    [numberFormatter setMinimumFractionDigits:0];
    [numberFormatter setMaximumFractionDigits:2];
}

NSNumber *numberInMM = [NSNumber numberWithFloat:fLenInMMs];
NSString *numberStr = [numberFormatter stringFromNumber:numberInMM];
numberStr = [numberStr stringByAppendingString:@" mm"];
4

1 回答 1

0
long long d = fLenInMMs;
if (d>9999) {
    NSNumberFormatter *numberFormatter=nil;
    if (numberFormatter == nil) {
        numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
        [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [numberFormatter setLocale:[NSLocale currentLocale]];
        [numberFormatter setMinimumFractionDigits:0];
        [numberFormatter setMaximumFractionDigits:2];
    }

    NSNumber *numberInMM = [NSNumber numberWithFloat:fLenInMMs];
    NSString *numberStr = [numberFormatter stringFromNumber:numberInMM];
    numberStr = [numberStr stringByAppendingString:@" mm"];
    NSLog(@"%@", numberStr);
}
else {
    NSNumber *numberInMM = [NSNumber numberWithFloat:fLenInMMs];
NSString *numberStr =   [NSString stringWithFormat:@"%@ mm",numberInMM];
} 

EDIT

You can also subclass NSNumberFormatter and implement

- (NSString *)stringFromNumber:(NSNumber *)number
{
    NSNumber *nm = [NSNumber numberWithInt:9999];

    if (NSOrderedAscending==[number compare:nm]) {
        return [NSString stringWithFormat:@"%@ mm",number];
    }

    return [super stringFromNumber:number];
}
于 2012-10-22T12:54:36.277 回答