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:
NSNumberFormatter *formatString = [[NSNumberFormatter alloc] init];
formatString.decimalSeparator = @".";
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:
_myTextField.text = [NSString stringWithFormat:@”%.1f”, [_myNumber floatValue]];
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:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setMaximumFractionDigits:1];
_myTextField.text = [f stringFromNumber:_myNumber];
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