0

I want to make a text field with double number formatting as user is typing. I use this text field for currency input (without any currency symbols etc). Here's what I tried so far:

@IBAction func onEditingChanged(_ sender: UITextField) {
    let validString = sender.text!.replacingOccurrences(of: " ", with: "")
    let price = Double(validString)!

    let formatter = NumberFormatter()
    formatter.decimalSeparator = "."
    formatter.groupingSeparator = " "
    formatter.numberStyle = .decimal

    if let formattedTipAmount = formatter.string(from: price as NSNumber) {
        self.currencyTextField.text = formattedTipAmount
    }
}

However no matter how I try I cannot put a dot in my string to make this number double and as a result I can't edit/type the fractional part.

Here's how I see it should work:

User input 1: 2132

Displayed value in textfield: 2 132.00

User Input 2: 2132.54 (the user set a point before the dot separator and typed 54 to replace 00)

Output: 2 132.54

etc

Mr Jox
  • 75
  • 9
  • It's very unusual to format a numeric field while the user is typing and personally I would find it annoying if the text changed while typing it. – Joakim Danielson Aug 22 '18 at 12:24
  • @JoakimDanielson that's nothing but just formatting and unfortunately I have to strictly accomplish this task according to the design I was given – Mr Jox Aug 22 '18 at 12:40
  • 1
    First of all make the formatter a class property so you don't need to instantiate a new one for each call to `onEditingChanged`, secondly wouldn't it work if you used the formatter in both directions without and character replacement, `formatter.number(from:)`? – Joakim Danielson Aug 22 '18 at 12:51
  • @JoakimDanielson it works nearly perfect with exception of cursor pointer getting moved to the end. Is there a way to preserve it's position? – Mr Jox Aug 22 '18 at 12:57
  • I guess you could use the input string and see where the "." is (if there is one) and how many digits exists after it and set the cursor depending on that. "123." -> set cursor directly after dot, "123.4" -> set cursor after "4"... but it will be far from perfect – Joakim Danielson Aug 22 '18 at 13:11
  • https://stackoverflow.com/a/29783546/2303865 – Leo Dabus Aug 22 '18 at 16:49

0 Answers0