NSNumberFormatter weirdness with NSNumberFormatterPercentStyle
- by rein
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.