nebuto nebuto - 3 years ago 256
Swift Question

Convert currency string into float in Objective-C

My goal is simple, I have a textfield storing a localized currency value ($1,000.00 for instance) and I need to get that value back from the textfield as a float to perform some test on the textfield.

The code is really simple, first I format the NSNumber to a localizedString as so :

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
formatter.locale = [NSLocale currentLocale];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
textfield.text = [formatter stringFromNumber:number];


Everything works fine, but then I do the opposite to get the doubleValue from this localized string :

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
formatter.locale = [NSLocale currentLocale];
formatter.numberStyle = NSNumberFormatterCurrencyStyle; //also tested with NSNumberFormatterDecimalStyle

double d = [formatter numberFromString:textfield.text].doubleValue;


The problem is that the formatter only returns the integer value of my string and not the decimals, worse, if it is a canadian localizedstring (20 000,00 $) it only returns 20.

I've been searching for some time now and can't find anything about this behavior. The workaround is of course storing the NSNumber right before formating it to the textfield and then testing this nsnumber, but I really don't find it pretty.

Answer Source

The answer, as pointed by Giuseppe, is really simple and I'm bashing my head against the wall for not thinking about it.

double d = [NSDecimalNumber decimalNumberWithString:textfield.text locale:[NSLocale currentLocale]].doubleValue;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download