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?

CodeGrue
  • 5,865
  • 6
  • 44
  • 62

2 Answers2

1

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
  • 23,305
  • 6
  • 62
  • 80
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.

Lounges
  • 4,674
  • 5
  • 32
  • 43