NSNumberFormatter error from the Apple Documentation "Data Formatting Guide"
I follow the "Data Formatting Guide" from the Apple Developer website:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setFormat:@"0.00%;0.00%;-0.00%"];
NSNumber *four = [NSNumber numberWithFloat:4.0];
NSLog(@"%@", [numberFormatter stringFromNumber:four]);
But it throws an exception:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNumberFormatter setFormat:]: unrecognized selector sent to instance 0x59359b0'
The document was last updated on 2009, so I would not blame on that. My questions are: How do you deal with this error?
Edited Question
How开发者_如何学JAVA do you specify a format on NSNumber? How do you parse a string to a number, a number to string? How do you specify the patterns that Apple pointed to us in a document. I'm talking about iPhone programming. Thank you all!
Edited again
Let's generalize my question: If you take a look at the patterns, let's say I have a string "1 234,57 €" (the last one in the link) and I want to parse this string to a number, I need to specify the format as: "# ##0.00 ¤", but now for iPhone applications, as two people suggested, there's no setFormat: method.
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setFormat:@"# ##0.00 ¤"];
NSNumber *dollars = [numberFormatter numberFromString:@"1 234,57 €"];
How do you cope with this?
The link you are looking at is for Mac, not iOS NSNumberFormatterReference
try this:
[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
Doesn't look like there is a setFormat: method on a NSNumberFormatter class (even though it's all over the documentation!)
Try the setPositiveFormat: method instead?
Though looking at your example problem, this might be better :
NSLog(@"%f", 4.0f);
or, if you want to store it in a string :
NSString *myString = [NSString stringWithFormat:@"%f", 4.0f]; // You might need to retain this!
Take a look at the string formatting guide.
精彩评论