Using NSNumberFormatter to get a decimal value from an international currency string

Posted by Duncan A on Stack Overflow See other posts from Stack Overflow or by Duncan A
Published on 2010-08-24T20:44:20Z Indexed on 2010/12/25 2:54 UTC
Read the original article Hit count: 568

It seems that the NSNumberFormatter can't parse Euro (and probably other) currency strings into a numerical type. Can someone please prove me wrong.

I'm attempting to use the following to get a numeric amount from a currency string:

NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *currencyNumber = [currencyFormatter numberFromString:currencyString];

This works fine for UK and US currency amounts. It even deals with $ and £ and thousands separators with no problems.

However, when I use it with euro currency amounts (with the Region Format set to France or Germany in the settings app) it returns an empty string. All of the following strings fail:

12,34 €
12,34
12.345,67 €
12.345,67

It's worth noting that these strings match exactly what comes out of the NSNumberFormatter's stringFromNumber method when using the corresponding locale.

Setting the Region Format to France in the settings app, then setting currencyNumber to 12.34 in the following code, results in currencyString being set to '12,34 €' :

NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *currencyString = [currencyFormatter stringFromNumber:currencyNumber];

It would obviously be fairly easy to hack around this problem specifically for the Euro but I'm hoping to sell this app in as many countries as possible and I'm thinking that a similar situation is bound to occur with other locales.

Does anyone have an answer?

TIA, Duncan

© Stack Overflow or respective owner

Related posts about iphone

Related posts about cocoa