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:
This worked for me: Naming of the variables need to be improved though. Multiplying by 10 was easy but figuring out how to divide by 10 and round down was tricky with the pointers.
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == amountTextField {
guard let text = textField.text else {return true}
let oldDigits = numberFormatter.number(from: text) ?? 0
var digits = oldDigits.decimalValue
if let digit = Decimal(string: string) {
let newDigits: Decimal = digit / 100
digits *= 10
digits += newDigits
}
if range.length == 1 {
digits /= 10
var result = Decimal(integerLiteral: 0)
NSDecimalRound(&result, &digits, 2, Decimal.RoundingMode.down)
digits = result
}
textField.text = NumberFormatter.localizedString(from: digits as NSDecimalNumber, number: .currency)
return false
} else {
return true
}
}