简体   繁体   中英

NSNumberFormatter glitch

I have a strange problem. It only seems to present on a tester's iPhone 5s. It works correctly on an iPhone 5, 6 and 6 plus, all running the latest iOS (8.3).

This is the code

-(NSString *) commaString:(double)number
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    [numberFormatter setGroupingSize:3];
    [numberFormatter setMaximumSignificantDigits:9];
    NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble: number]];

    return numberAsString;
}

The application is a calculator and is usually presenting correctly like this

It is usually showing correctly like this 在此处输入图片说明
but on this iPhone 5s it is showing like this 在此处输入图片说明

I thought the setMaximumSignificantDigits would have nipped this in the bud, but it's still showing the same. Could this be some strange localisation thing? I don't think it is as his iPhone 6 it is showing correctly also.
Thanks
Luke

If your goal is to simply have commas every three characters, all you need to do is:

    NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;

    NSNumber * numberFromString = [numberFormatter numberFromString:currentTextWithoutCommas];
    NSString * formattedNumberString = [numberFormatter stringFromNumber:numberFromString];

If you're finding that there's an issue with localizing the formatter, then set secondaryGroupingSize to 3. As written in the docs for NSNumberFormatter :

Some locales allow the specification of another grouping size for larger numbers. For example, some locales may represent a number such as 61, 242, 378.46 (as in the United States) as 6,12,42,378.46. In this case, the secondary grouping size (covering the groups of digits furthest from the decimal point) is 2.

Also, you can check out Formatting Numbers on iOSDeveloperTips for a brief, high-level overview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM