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

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:

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:

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?

Note: I used the [textField.text floatValue] method.


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:


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?


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

You can use:

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

this is ok for all the languages.

Need Your Help

Initializing `constexpr` Array with Pattern

c++ templates c++11 template-meta-programming constexpr

I would like to initialize a constexpr array with a pattern that is generated using variadic template parameters. For simplicity, consider the problem of initializing a constexpr unsigned static ar...

Second onClick listener in a new activity

android android-studio onclick onclicklistener

I just started to learn Java. I know some C++, but you know, I am just a novice. I have a problem with a button. I a main activity there are 3 buttons with onClick discovered by switch. By clicking...