UIKeyboardTypeDecimalPad中的小数点不能用于数学计算 [英] Decimal point in UIKeyboardTypeDecimalPad can't be used in mathematical calculation
问题描述
我正在使用键盘类型: UIKeyboardTypeDecimalPad
,用于两个 UITextField
对象。
尝试执行添加时,根据当前区域设置得到不同的结果:
I am using the keyboard type: UIKeyboardTypeDecimalPad
for two UITextField
objects.
When trying to perform an addition, I get different results depending on the current locale:
案例1:美国格式:小数点显示为。
按预期方式。如果我添加12.3(文本字段1)+ 12.3(文本字段2),答案将是24.6。这就是我想要的。但是:
Case 1: US Format: the decimal point appears as .
as expected. If I add 12.3 (text field 1) + 12.3 (text field 2), the answer will be 24.6. That's what I want. But:
案例2:埃及格式:小数点显示为,
。如果我重复相同的计算,答案将是24.小数部分被忽略。有没有修复?
Case 2: Egypt Format: the decimal point appears as ,
. If I repeat the same calculation the answer will be 24. The decimal portion is ignored. Is there a fix for that?
注意:我使用 [textField.text floatValue]
方法。
推荐答案
因为 floatValue
进行非本地化扫描,它需要美国格式 。
Because floatValue
does non-localized scanning, it expects a "US format".
您可以使用NSScanner对象对字符串中的数值进行本地化扫描。
You can use an NSScanner object for localized scanning of numeric values from a string.
请参阅: 字符串编程指南:扫描仪
注意最后一段:
本地化
扫描程序将某些扫描行为基于区域设置,
指定了值表示的语言和约定。
NSScanner仅使用小区分隔符
的区域设置定义(由名为NSDecimalSeparator的密钥给出)。您可以使用localizedScannerWithString:使用用户的语言环境创建扫描程序
,或使用setLocale:显式设置
语言环境。如果您使用
未指定区域设置的方法,则扫描程序将采用默认区域设置
值。
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中进行字符串转换?
示例:
NSScanner *scanner = [NSScanner localizedScannerWithString:textField.text];
double mynumber;
if([scanner scanDouble: &mynumber]){
// do something
};
这篇关于UIKeyboardTypeDecimalPad中的小数点不能用于数学计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!