javaandroidkotlintextwatcher

Android Editable on TextWatcher not appending correctly


I´m adding a Thousands separator on my TextWatcher

Code:

override fun afterTextChanged(s: Editable) {
    var initial = s.toString()

    if (!TextUtils.isEmpty(initial)) {
        initial = initial.replace(".", "")
        val formatSymbols = DecimalFormatSymbols()
        formatSymbols.groupingSeparator = '.'
        val formatter: NumberFormat = DecimalFormat("###,###,###", formatSymbols)
        editText.removeTextChangedListener(this)
        val myNumber = initial.toDouble()
        val processed: String = formatter.format(myNumber)
        s.clear()
        s.append(processed)
        editText.addTextChangedListener(this)
    }
}

For testing, I input the number 1000, and it works fine. It outputs 1.000 Input 100000 and works fine again, output is 100.000 For some reason, when I input 1000000, the processed variable is 1.000.000, but when I append to the Editable, it appends as 1000.000

Image showing the variable Processed is correct, but the appended result isn´t

Image showing the variables value

Any ideas as to why it´s happening?

I could set the text of the edittext directly, but that´s not my goal right now


Solution

  • Okey so the code was indeed working correctly. Apparently the issue was the InputType I was using for the keyboard, which was: InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL

    Totally my bad

    No idea how to make the keyboard so it shows just numbers, yet make it work with the filter i´m using, but that´s atleast an issue I can work on

    Thanks everyone for the help!