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
}
}
}
In Swift 4.
TextField have 10 digit limit and after decimal 2 digit limit (you can change the Limits). The dot will allow only one time in the textField.
class ViewController: UIViewController,UITextFieldDelegate {
var dotLocation = Int()
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let nonNumberSet = CharacterSet(charactersIn: "0123456789.").inverted
if Int(range.length) == 0 && string.count == 0 {
return true
}
if (string == ".") {
if Int(range.location) == 0 {
return false
}
if dotLocation == 0 {
dotLocation = range.location
return true
} else {
return false
}
}
if range.location == dotLocation && string.count == 0 {
dotLocation = 0
}
if dotLocation > 0 && range.location > dotLocation + 2 {
return false
}
if range.location >= 10 {
if dotLocation >= 10 || string.count == 0 {
return true
} else if range.location > dotLocation + 2 {
return false
}
var newValue = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
newValue = newValue?.components(separatedBy: nonNumberSet).joined(separator: "")
textField.text = newValue
return false
} else {
return true
}
}
}