Search code examples
iphoneobjective-cnsnumberformatter

Conditional NSNumberFormatterCurrencyStyle handling


I have two currency values: £2.60 and £22,000. Both are stored as NSDecimalNumber in Core Data. I create a string from them using the following:

    // The app will be GB only, which is the reason locale is set to en_GB
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setLocale: locale];
    [formatter setNumberStyle: NSNumberFormatterCurrencyStyle];

    // job is a Core Data entity, value1 and value2 or NSDecimalNumbers
    NSString *value1 = [formatter stringFromNumber: [job value1]]; // 2.60
    NSString *value2 = [formatter stringFromNumber: [job value2]];    // 22000
    NSString *testString = [NSString stringWithFormat:@"%@ and %@", value1, value2];

This as a whole works ok, but testString prints as £2.60 and £22,000.00.

What would be the best way implement [formatter setMaximumFractionDigits: 0]; for the largeValue only?


Solution

  • The answer depends on your formatting requirements, but I think a good heuristic would be to chop off the decimal digits when the number shows a thousands separator:

    if ([[job value2] doubleValue] >= 1000.0) {
        [formatter setMaximumFractionDigits: 0];
    }