How can I change a UITextField, that the User can just add one . and only two digits after the . -> Decimal Number with two digits after the poi^nt.
Asked
Active
Viewed 123 times
-2
-
Please don't hesitate to provide what have you tried so far... – Ahmad F Jul 02 '18 at 11:48
-
Keep in mind that many people around the world do not use the `.` as the decimal separator. – rmaddy Jul 02 '18 at 16:33
1 Answers
1
Use UITextFieldDelegate
// MARK:- TEXTFIELD DELEGATE
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
let countdots = (txf_Amount.text?.components(separatedBy: ".").count)! - 1
if countdots > 0 && string == "."
{
return false
}
let MAX_BEFORE_DECIMAL_DIGITS = 7
let MAX_AFTER_DECIMAL_DIGITS = 3
let computationString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
// Take number of digits present after the decimal point.
let arrayOfSubStrings = computationString.components(separatedBy: ".")
if arrayOfSubStrings.count == 1 && computationString.characters.count > MAX_BEFORE_DECIMAL_DIGITS {
return false
} else if arrayOfSubStrings.count == 2 {
let stringPostDecimal = arrayOfSubStrings[1]
return stringPostDecimal.characters.count <= MAX_AFTER_DECIMAL_DIGITS
}
return true
}

Yogesh Tandel
- 1,738
- 1
- 19
- 25
-
This is not a good solution since not all users use `.` as a decimal separator. – rmaddy Jul 02 '18 at 16:33