Uitextfield's Numerical Pad: Dot Instead of Comma for Float Values

UITextField's numerical pad: dot instead of comma for float values

Potential duplicate of the SO Answer, use NSNumberFormatter

Example Swift:

let number = NSNumberFormatter().numberFromString(numberString)
if let number = number {
let floatValue = Float(number)
}

Example (Objective-C):

NSNumber *number = [[NSNumberFormatter new] numberFromString: numberString];
float floatValue = number.floatValue;

Decimal pad can't do math with comma. Need dot

You want the decimal keypad to have either a comma or a period (dot) based on the user's locale. This is so the user can enter the value as they are accustomed to. In order for you to do the math with the vales, you need to use a NSNumberFormatter to convert the entered string into a double value. Once you do this, your math formulas will work. Never use doubleValue or floatValue to convert an NSString to a double or float if the string was entered by the user. Always use NSNumberFormatter to properly deal with the user's locale.

Update based on code added to question.

You don't use the number formatter. You are doing exactly what I said not to do. Change your code to:

double firstValue = [[nf numberFromString:myString] doubleValue];
double secondValue = [[nf numberFromString:myOtherString] doubleValue];
double result = firstValue * secondValue;

DecimalPad has Comma rather than Dot

Users expect numbers (and dates, times, and other information) to be entered and viewed in their own local format. iOS takes care of this based on their locale. An app should honor these settings.

A comma appears on the number pad when the user's device is set to a region (which affects their locale) that normally uses a comma as the decimal separator. Other symbols (such as a period) will appear depending on the user's locale.

When writing an app that accepts number entry and displays numbers to the user, it is best to use NumberFormatter to convert the entered strings into numeric data types and to convert numeric data type into strings. This ensures users can enter and view numbers (and dates, etc.) in the format they normally use in their every day life.

As it turned out, your own iPhone had an unexpected Region setting that caused the comma to appear on the number pad instead of your own expectation of a period. This appears to have led to some confusion.



Related Topics



Leave a reply



Submit