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?
Swift 5. Adding to Enrique's answer (based on Code Different baseline), I found the need to allow the Delete key to operate anywhere on the line along with a sign (+ or -) or decimal point at the beginning of the input line.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Limit number fields to +/- Real #s: sign as first character, one decimal separator, one decimal place after separator
if string.isEmpty { return true } // Allow delete key anywhere!
guard let oldText = textField.text, let rng = Range(range, in: oldText) else {
return true
}
let newText = oldText.replacingCharacters(in: rng, with: string)
let isNumeric = newText.isEmpty || (Double(newText) != nil)
let formatter = NumberFormatter()
formatter.locale = .current
let decimalPoint = formatter.decimalSeparator ?? "."
let numberOfDots = newText.components(separatedBy: decimalPoint).count - 1
let numberOfDecimalDigits: Int
if let dotIndex = newText.firstIndex(of: ".") {
numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
} else {
numberOfDecimalDigits = 0
}
if newText.count == 1 && !isNumeric { // Allow first character to be a sign or decimal point
return CharacterSet(charactersIn: "+-" + decimalPoint).isSuperset(of: CharacterSet(charactersIn: string))
}
return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 1
}