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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With