NSNumberFormatter returns nil on the device, not on the simulator

I use NSNumberFormatter to convert user input to NSNumber (decimal), I use ARC.

NSNumberFormatter *f = [[NSNumberFormatter alloc] init]; [f setNumberStyle:NSNumberFormatterDecimalStyle]; [f setMaximumFractionDigits:1]; _myNumber = [f numberFromString:myTextField.text]; 

Sometimes this results in _myNumber as nil . Even when I'm absolutely sure that user input is the correct decimal number (I checked during debugging).

For completeness: _myNumber is a synthesized property of the ViewController. This only happens when the application is launched on the device, and not when it is launched in the simulator. The keyboard used is the Decimal Panel. In another section of code in another ViewController, the code really works.

Now I have a workaround that I added below the code above:

 if (!myNumber){ myNumber = [NSNumber numberWithFloat: myTextField.text.floatValue]; } 

Does anyone know why NSNumberFormatter can return zero even when [NSNumber numberWithFloat: myTextField.text.floatValue] ?

+4
source share
3 answers

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

 NSNumberFormatter *formatString = [[NSNumberFormatter alloc] init]; formatString.decimalSeparator = @"."; 
+6
source

Why it worked on the simulator, and not on the device, depended on the language settings. My simulator is set to English when my device is set to Dutch. When in English "." It is used as a decimal separator when the symbol "," is used in Dutch.

When writing the original value to a UITextField, I used the following code:

 _myTextField.text = [NSString stringWithFormat:@"%.1f", [_myNumber floatValue]]; 

The result is always "." as a decimal separator, which may or may not be correct depending on the language settings. I needed to use NSNumberFormatter to set the value in a UITextField:

 NSNumberFormatter *f = [[NSNumberFormatter alloc] init]; [f setNumberStyle:NSNumberFormatterDecimalStyle]; [f setMaximumFractionDigits:1]; _myTextField.text = [f stringFromNumber:_myNumber]; 
+2
source

I had the same problem, but not with text input, but with API consumption, where the decimal separator is ".". Using the DecimalNumberFormatter method fails on my devices (Germany uses ","), but not on the simulator (which can use the "US Region" setting).

My solution is to define a decimal separator and provide it to the formatting object:

  f.decimalSeparator = "." 
0
source

All Articles