I use a NSNumberFormatter to convert a user input to a NSNumber (a decimal number), I use ARC.
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setMaximumFractionDigits:1];
_myNumber = [f numberFromString:myTextField.text];
Sometimes this results in _myNumber
to be nil
. Even when I am absolutely sure the users input is a correct decimal number (I checked during debugging).
For completeness: _myNumber
is a synthesized property of the ViewController.
This only happens when running the app on a device, not when I run it in the simulator.
The keyboard being used is the ‘Decimal Pad’
In a different section of code, in a different ViewController the code does work.
I now have a workaround which I have added below the above code:
if (!myNumber){
myNumber = [NSNumber numberWithFloat: myTextField.text.floatValue];
}
Does anybody know why NSNumberFormatter can return nil, even when calling [NSNumber numberWithFloat: myTextField.text.floatValue]
works?
In my case the solution was set the "decimalSeparator" for the NSNumberFormatter to ".", example:
Why this was working on the simulator and not on the device depended on the Language settings. My simulator is set to English while my device is set to Dutch. When in English a “.” is used as a decimal separator, when in Dutch a “,” is used.
When writing the original value to the UITextField I used the following code:
This results in always having the “.” as a decimal separator which may or may not be correct depending on the Language settings. What I had to do was to use a NSNumberFormatter to set the value into the UITextField:
I had the same Problem but not with Text input but with consuming a API where the decimal separator is ".". Using an DecimalNumberFormatter fails on my Devices (Germany uses ",") but not on the Simulator (which may uses the US Region setting).
My fix is to determine the decimal separator and providing it to the formatter object: