NSNumberFormatter weirdness with NSNumberFormatterPercentStyle
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] auto开发者_高级运维release];
[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.
Known bug.
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);
}
精彩评论