views:

167

answers:

2

Hi,

I need to parse some text in a UITextField and turn it into a percentage. Ideally, I'd like the user to either type something like 12 or 12% into the text field and have that be parsed into a number as a percentage.

Here's what's weird. The number formatter seems to not like 12 and seems to divide 12% by 10000 instead of 100:

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterPercentStyle];

NSNumber *n1 = [formatter numberFromString:@"12"];   
NSNumber *n2 = [formatter numberFromString:@"12%"];  

NSLog(@"n1 = %@", n1);  // n1 = (null)
NSLog(@"n2 = %@", n2);  // n2 = 0.0012

How do I get the formatter to return 0.12 as expected?

EDIT: it seems to only happen if the formatter fails first. If the formatter does not fail it returns 0.12 as expected. Strange.

+2  A: 

Known bug.

KennyTM
Thanks. Wow, found almost two years ago. A bit surprising that a bug like this hasn't been fixed yet since it can seriously affect financial systems.
rein
@rein: The problem I think is because the bug is in Apple, but ICU. NSNumberFormatter is just a front-end of ICU's UNumberFormat. (Of course we can blame Apple for using an ancient version (4.0) of ICU.)
KennyTM
@KennyTM: thanks for the clarification. I've worked around the issue.
rein
A: 

Here's a workaround that seemed to work for me:

I subclassed NSNumberFormatter and implemented the following methods. Seemed to work for me.

- (NSNumber *)numberFromString:(NSString *)string { 
    NSNumber *retValue = [super numberFromString:string];
    if ([self numberStyle] ==   NSNumberFormatterPercentStyle) {
        [super setNumberStyle:NSNumberFormatterPercentStyle];   
    }
    return (retValue);
}

- (NSString *)stringFromNumber:(NSNumber *)number {
    NSString * str = [super stringFromNumber:number];
    if ([self numberStyle] ==   NSNumberFormatterPercentStyle) {
        [super setNumberStyle:NSNumberFormatterPercentStyle];   
    }
    return (str);
}
Martin Stanley