Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 332
nebuto Avatar asked Oct 07 '22 00:10

nebuto


2 Answers

In Swift, you can do this by similarly setting the locale to the format of the currency, and then getting the double:

    var locale = NSLocale.currentLocale()
    var formatter = NSNumberFormatter()
    formatter.locale = NSLocale(localeIdentifier: "en_US")
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle

    var moneyDouble = formatter.numberFromString(textField.text)?.doubleValue
like image 75
Gabriel Garrett Avatar answered Oct 10 '22 01:10

Gabriel Garrett


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;
like image 24
nebuto Avatar answered Oct 10 '22 02:10

nebuto