I have a textField where user can enter a number which can has a decimals. I want to restrict the amount of decimal characters possible to enter till 4.
I'm trying to reach this behaviour with this code:
let split = completeString.components(separatedBy: ".")
if split.count == 2 {
print(split.last!)
if split.last!.count >= 4 {
return false
}
}
Full code for shouldChangeCharactersIn
method:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let formatter = converterManager.setupNumberFormatter()
let textString = textField.text ?? ""
guard let range = Range(range, in: textString) else { return false }
let updatedString = textString.replacingCharacters(in: range, with: string)
let correctDecimalString = updatedString.replacingOccurrences(of: ",", with: ".")
let completeString = correctDecimalString.replacingOccurrences(of: formatter.groupingSeparator, with: "")
let split = completeString.components(separatedBy: ".")
if split.count == 2 {
print(split.last!)
if split.last!.count >= 4 {
return false
}
}
numberFromTextField = completeString.isEmpty ? 0 : Double(completeString)
guard completeString.count <= 12 else { return false }
guard !completeString.isEmpty else { return true }
textField.text = formatter.string(for: numberFromTextField)
return string == formatter.decimalSeparator
}
}
This code successfully split the string, give me the numbers user enters after decimal sign, but:
- textField shows 3 character instead of 4
- print shows that despite textField shows 3, when I press 4th digits in shows in the split array
- when after 4th digit I continue to press numbers it changes last digit. I want if there is a 4 numbers entered already allow only delete not change the last number
GIF with behaviour: https://cln.sh/5vf1iq
How to fix that behaviour?
Splitting based on .
is not a good approach here. E.g. plenty of cultures would write 10.5 as 10,5 and 1,000 as 1.000, so the period and the comma is reversed. You should look into NSNumberFormatter
. It can convert strings to numbers and vice versa and allows you to set all sorts of limits such as number of decimals.