views:

581

answers:

3

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?

A: 

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.

Tom Dalling
+2  A: 

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.

Lounges
A: 

You can still use NSCurrencyFormatter, you just need to do it more "manually" by specifying the maximumFractionDigits.

An example was posted here: Obtaining an NSDecimalNumber from a locale specific string

Gorthmog