Cocoa NSNumberFormatterCurrencyStyle without “$” return zero

你说的曾经没有我的故事 提交于 2019-12-22 10:33:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!