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

别等时光非礼了梦想. 提交于 2019-12-02 01:34:06
magma

Because floatValue does non-localized scanning, it expects a "US format".

You can use an NSScanner object for localized scanning of numeric values from a string.

See: String Programming Guide: Scanners

Note the last paragraph:

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.

See also: How to do string conversions in Objective-C?

Example:

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

You can use:

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

this is ok for all the languages.

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