What is the best way to enter numeric values with decimal points?

In my app users need to be able to enter numeric values with decimal places. The iPhone doesn't provides a keyboard that's specific for this purpose - only a number pad and a keyboard with numbers and symbols.

Is there an easy way to use the latter and prevent any non-numeric input from being entered without having to regex the final result?

Thanks!


Solution 1:

I think it would be good to point out that as of iOS 4.1 you can use the new UIKeyboardTypeDecimalPad.

So now you just have to:

myTextField.keyboardType=UIKeyboardTypeDecimalPad;

Solution 2:

A more elegant solution happens to also be the simplest.

You don't need a decimal separator key

Why? Because you can simply infer it from the user's input. For instance, in the US locale when you what to enter in $1.23, you start by entering the numbers 1-2-3 (in that order). In the system, as each character is entered, this would be recognized as:

  • user enters 1: $0.01
  • user enters 2: $0.12
  • user enters 3: $1.23

Notice how we inferred the decimal separator based on the user's input. Now, if the user wants to enter in $1.00, they would simply enter the numbers 1-0-0.

In order for your code to handle currencies of a different locale, you need to get the maximum fraction digits of the currency. This can be done with the following code snippet:

NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
int currencyScale = [currencyFormatter maximumFractionDigits];

For example, the Japanese yen has a maximum fraction digit of 0. So, when dealing with yen input, there is no decimal separator and thus no need to even worry about fractional amounts.

This approach to the problem allows you to use the stock numeric input keypad provided by Apple without the headaches of custom keypads, regex validation, etc.