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?
None of the answers handled the decimalSeparator and all the edge cases I came across so I decided to write my own.
extension YourController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text, let decimalSeparator = NSLocale.current.decimalSeparator else {
return true
}
var splitText = text.components(separatedBy: decimalSeparator)
let totalDecimalSeparators = splitText.count - 1
let isEditingEnd = (text.count - 3) < range.lowerBound
splitText.removeFirst()
// Check if we will exceed 2 dp
if
splitText.last?.count ?? 0 > 1 && string.count != 0 &&
isEditingEnd
{
return false
}
// If there is already a dot we don't want to allow further dots
if totalDecimalSeparators > 0 && string == decimalSeparator {
return false
}
// Only allow numbers and decimal separator
switch(string) {
case "", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", decimalSeparator:
return true
default:
return false
}
}
}