问题
I have a number formatter set up to convert currency strings to decimal values. The problem is that if the text string does not have a leading dollar sign ("$"), it gets converted to 0, rather than a valid matching number. So:
"$3.50" converts to 3.50
"3.50" converts to 0
Here is the code for the converter:
// formatter to convert a value to and from a currency string
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setGeneratesDecimalNumbers:YES];
Am I missing something?
回答1:
I ran into a similar problem. I ended up scrapping the NSNumberFormatter for parsing and switched over to RegexKit Lite with much better results.
Grab a copy here: RegexKit Lite
Then go here http://regexlib.com/ and find the regex that works best for you.
回答2:
It's converting "3.50" to 0 because it doesn't recognize "3.50" as a valid currency string as mentioned here: http://blog.clickablebliss.com/2006/10/05/the-challenges-of-international-money-in-cocoa/. If the default NSNumberFormatterCurrencyStyle isn't flexible enough for your needs, you may need to subclass it to handle these cases.
来源:https://stackoverflow.com/questions/1156347/cocoa-nsnumberformattercurrencystyle-without-return-zero