Home > Enterprise >  How could I add or substract Two EditTex Values currency formatted with a TextWatcher?
How could I add or substract Two EditTex Values currency formatted with a TextWatcher?

Time:08-02

I want to calculate user repayment capacity by subtracting users input from two formatted and text-watched editTexts. However, I'm getting this error:

java.lang.NumberFormatException: For input string: "100,000.0"

I used https://github.com/BlacKCaT27/CurrencyEditText and https://github.com/zihadrizkyef/TextWatcherForMoney with no success. Here's my code:

ingresos.addTextChangedListener(CurrencyTextWatcher(ingresosEditText))


val IngresosNetos =
(ingresos.text.toString().toInt() - egresos.text.toString().toInt())
val formatear = NumberFormat.getCurrencyInstance().format(IngresosNetos)
val formateados = "$formatear"
capacidadpagotv.text = formateados

Any help would be appreciated. Thanks.

CodePudding user response:

The standard way for number parsing as far as i know, is '.' for decimals, and no "," for separating the thousands/millions, etc. Because of this, your strings can't be parsed to a valid numerical value.

By loooking at the library you are using, they provide a getRawValue() for

Providing back the raw numeric values as they were input by the user, and should be treated as if it were a whole value of the users local currency. For example, if the text of the field is $13.37, this method will return a Long with a value of 1337, as penny is the lowest denomination for USD.

My advice would be to use this instead of your current approach since handling different locale/standard where '.' and ',' shift around is very hard to accomplish reliably.

Edit: The library's MavenCentral repo seems to be missing, so you should use the jitpack one.

    maven { url "https://jitpack.io" }

and implementation 'com.github.BlacKCaT27:CurrencyEditText:2.0.2'

This works for me

<com.blackcat.currencyedittext.CurrencyEditText
        android:id="@ id/myCurrency"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

val curencyValue = binding.myCurrency.rawValue // returns a long

and to then set the value, use the formatCurrency from the same library.

binding.myCurrency.formatCurrency(curencyValue.toString())
  • Related