关于iphone:UIKeyboardTypeDecimalPad中的小数点不能用于数学计算

Decimal point in UIKeyboardTypeDecimalPad can't be used in mathematical calculation

我正在使用键盘类型:UIKeyboardTypeDecimalPad用于两个UITextField对象。
尝试执行添加时,我会根据当前区域设置得到不同的结果:

情况1:美国格式:小数点按预期显示为.。 如果我添加12.3(文本字段1)+ 12.3(文本字段2),答案将是24.6。 这就是我想要的。 但:

案例2:埃及格式:小数点显示为,。 如果我重复相同的计算,答案将是24.小数部分被忽略。 有没有修复?

注意:我使用了[textField.text floatValue]方法。


因为floatValue进行非本地化扫描,所以它需要"美国格式"。

您可以使用NSScanner对象对字符串中的数值进行本地化扫描。

请参阅:字符串编程指南:扫描仪

注意最后一段:

Localization

A scanner bases some of its scanning behavior on a locale, which
specifies a language and conventions for value representations.
NSScanner uses only the locale’s definition for the decimal separator
(given by the key named NSDecimalSeparator). You can create a scanner
with the user’s locale by using localizedScannerWithString:, or set
the locale explicitly using setLocale:. If you use a method that
doesn’t specify a locale, the scanner assumes the default locale
values.

另请参见:如何在Objective-C中进行字符串转换?

例:

1
2
3
4
5
NSScanner *scanner = [NSScanner localizedScannerWithString:textField.text];
double mynumber;
if([scanner scanDouble: &mynumber]){
  // do something
};

您可以使用:

1
double number = [[self.myTextField.text stringByReplacingOccurencesOfString:@"," withString:@"."] doublevalue];

这对所有语言都可以。