EditText Number Formatting (ex: 123.456,23) Kotlin

102 Views Asked by At

I need to format my EditText in real time with the format (###.###,##) i tried everything i could find and nothing seems to work for my case example 1: if a user input '23' the result should be '0.23' example 2: if a user input '11123456' the result should be '111.234,56'

1

There are 1 best solutions below

0
Kevin Coppock On

You can make use of the TextWatcher interface for this. The afterTextChanged callback will fire whenever the contents of the EditText are modified, and you can make further modifications yourself within this callback (taking care to avoid recursive entry).

Something like this should get you close, at least:

class NumericFormattingTextWatcher : TextWatcher {
  private val formatter = NumberFormat.getInstance()
  private var skipNextChange = false
  
  override fun afterTextChanged(content: Editable) {
    if (skipNextChange) return

    skipNextChange = true
    val formatted = formatter.format(content.toString())
    content.replace(0, content.length(), formatted, 0, formatted.length())
    skipNextChange = false
  }

  override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
  override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
}

Then add this on your EditText:

editText.addTextChangedListener(NumericFormattingTextWatcher())

You'll also want to handle invalid input when formatting (e.g. if the user enters "11.22.33.44").