Decimal comma in textfield

Hi everyone,

today I have another question.

When I select the decimal pad to enter only numbers onto a text field, if I press twice or more the comma, the textfield doesn't limitate to one comma. And my code doesn't work because it doesn't recognize the number. How can I do to limitate to one comma entry in the textfield?

Accepted Answer

You can simply filter the text.

You can either do it during typing


Connect Editing Changed event to an IBAction


     @IBAction func editingTestField(_ sender: UITextField) {
          print(sender.text!)
          if Double(sender.text!) != nil {
               print("Num")
          } else {
               print("Not Num")
               sender.text!.removeLast()     // the double . or any alpha will disappear
          }
     }



Or at the end by checking the text is effectively a number


and, BTW, check if you should close the other threads you have opened, by marking correct answer or telling if there is still a problem.

Thanks Claude

Now I find another trouble. On the decimal pad appears a comma as decimal, and my text field doesn't recognize the comma as decimal. How can I change it to dot?

That's in simulator or on device ?


What is the problem ? Isn't your number recognized as number ?


It is a question of locale keyboard ; if you set language to US (in system settings), that should make it to dot.


May have a look here h ttps://stackoverflow.com/questions/30150829/uitextfields-numerical-pad-dot-instead-of-comma-for-float-values

Decimal comma in textfield
 
 
Q