NSNumberFormatter returns nil on device, not on simulator

一曲冷凌霜 提交于 2019-12-01 06:53:29
Cesar Chavez

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];

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:

    f.decimalSeparator = "."
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!