Formating a string from right to left for currency values

Viewed 44

I'm working on creating a way to input an amount and format it from left to right with placeholder zeros.

For example, pressing 1 and 2 would show $0.12 pressing 3 would give $1.23. Pressing backspace would give $0.12.

Instead, I am getting $1,0002.00

binding.keypad.btnBackspace.setOnClickListener {
    val text = binding.tvTotalValue.text.toString()

    if(text.isNotEmpty()) {
        binding.tvTotalValue.text = text.drop(1)
    }

    binding.tvTotalValue.text = ""
}

binding.keypad.onNumberSelected = {
    processNewAmount(it.toString())
}

private fun processNewAmount(newValue: String) {
    val text =  binding.tvTotalValue.text.toString().plus(newValue)
    val result = text.replace("[^0-9]".toRegex(), "") // remove any characters
    val amount = result.toDouble()
    binding.tvTotalValue.text = NumberFormat.getCurrencyInstance().format(amount)
}

What am I doing wrong?

Is there a better way to do this?

1 Answers

I advise keeping a property that stores the entered value without formatting. Each time a number is added, you can add it to this entered number and then format it for the screen. That will be a lot simpler than trying to move/remove existing symbols around in the String.

private var enteredNumber = ""

//...

binding.keypad.btnBackspace.setOnClickListener {
    enteredNumber = enteredNumber.dropLast(1)
    refreshTotal()
}

binding.keypad.onNumberSelected = {
    if(!(it == 0 && enteredNumber == "0")) { // avoid multiple zeros or backspace will act unexpectedly
        enteredNumber += it.toString()
        refreshTotal()
    }
}

//...

private fun refreshTotal() {
    val amount = enteredNumber.toDouble() / 100.0
    binding.tvTotalValue.text = 
        NumberFormat.getCurrencyInstance().format(amount)
}
Related