Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumberFormatter returns nil on device, not on simulator

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?

like image 321
Brabbeldas Avatar asked Jan 14 '23 16:01

Brabbeldas


2 Answers

In my case the solution was set the "decimalSeparator" for the NSNumberFormatter to ".", example:

NSNumberFormatter *formatString = [[NSNumberFormatter alloc] init];
formatString.decimalSeparator = @".";
like image 163
Cesar Chavez Avatar answered Jan 23 '23 00:01

Cesar Chavez


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];
like image 31
Brabbeldas Avatar answered Jan 23 '23 02:01

Brabbeldas