I am trying to format currency input in a textfield in Swift as the user inputs it.
So far, I can only format it successfully when the user finishes inputting:
Swift 5
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // return NO to not change text
switch string {
case "0","1","2","3","4","5","6","7","8","9":
currentString += string
formatCurrency(string: currentString)
default:
if string.count == 0 && currentString.count != 0 {
currentString = String(currentString.dropLast())
formatCurrency(string: currentString)
}
}
return false
}
func formatCurrency(string: String) {
print("format \(string)")
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.currency
formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale
let numberFromField = (NSString(string: currentString).doubleValue)/100
//replace billTextField with your text field name
self.billTextField.text = formatter.string(from: NSNumber(value: numberFromField))
print(self.billTextField.text ?? "" )
}