处理模拟器和设备之间的小数分隔符更改

Osc*_*and 0 number-formatting ios

我在我的应用程序中使用双打做一些数学运算.这在模拟器上很有效,模拟器使用句点来生成小数.当我在我的iPhone上运行时,我有一个逗号.当我使用逗号时它不会做任何事情.

如何修改所以要么认为逗号的东西作为一个周期或更改键盘(我用的是十进制垫),所以我得到的所有语言输入时期?

ipm*_*mcc 5

正如@propstm所说,不同的区域/区域设置使用不同的数字分隔符. NSScanner是用于将文本转换为数字类型的标准框架类,并且考虑了用户当前区域设置的所有约定.您应该将它用于从文本输入到双精度的转换.

但是,简单地用句点替换逗号是不够的,因为例如在美国区域设置$ 1,234.56是货币的有效值.如果您只是用句点替换逗号,则会变为无效.

使用NSScanner.这是它专门为其设计的.

编辑

您也可以考虑使用NSNumberFormatter与您的UITextField.在您进行扫描之前,它可以真正帮助验证用户输入NSScanner. 看看吧.

NSNumberFormatter使用示例:

将viewController设置为UITextField的委托,并添加以下方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *proposedNewValue = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    return (nil != [numberFormatter numberFromString:resultString]);
}
Run Code Online (Sandbox Code Playgroud)

这将使该字段不接受格式不正确的数字.您也可以使用此方法NSNumber从文本中获取.

要使用NSScanner你可以做这样的事情:

- (IBAction)doStuff:(id)sender
{
    NSString* entry = textField.text;
    double value = 0;

    if ([[NSScanner scannerWithString:entry] scanDouble: &value])
    {
        // If we get here, the scanning was successful
    }
    else
    {
        // Scanning failed -- couldn't parse the number... handle the error
    }
}
Run Code Online (Sandbox Code Playgroud)

HTH.