NSNumberFormatter weirdness with NSNumberFormatterPercentStyle

Posted by rein on Stack Overflow See other posts from Stack Overflow or by rein
Published on 2010-04-04T13:23:53Z Indexed on 2010/04/04 13:33 UTC
Read the original article Hit count: 483

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.

© Stack Overflow or respective owner

Related posts about iphone

Related posts about cocoa-touch