I have a textfield and I want to limit the entry to max 2 decimal places.
number like 12.34 is allowed but not 12.345
How do I do it?
Following the Code Different's answer, I've improved the code to support a different Locale and different UITextFields in the same class.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard textField.keyboardType == .decimalPad, let oldText = textField.text, let r = Range(range, in: oldText) else {
return true
}
let newText = oldText.replacingCharacters(in: r, with: string)
let isNumeric = newText.isEmpty || (Double(newText) != nil)
let formatter = NumberFormatter()
formatter.locale = Locale.current
let decimalPoint = formatter.decimalSeparator ?? "."
let numberOfDots = newText.components(separatedBy: decimalPoint).count - 1
let numberOfDecimalDigits: Int
if let dotIndex = newText.index(of: ".") {
numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
} else {
numberOfDecimalDigits = 0
}
return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 2
}