just
just

Reputation: 2010

Android DecimalFormat doesn't format correctly

I use DecimalFormat in a TextWatcher, here is my code:

override fun afterTextChanged(p0: Editable?) {
            amountEt?.removeTextChangedListener(this)

            var df = DecimalFormat("#,###.##")
            df.maximumFractionDigits = 2
            df.minimumFractionDigits = 0
            if (hasFractionalPart) {
                df.isDecimalSeparatorAlwaysShown = true
            }
            try {
                val inilen: Int
                val endlen: Int
                inilen = amountEt?.text!!.length

                var text: String? = p0.toString().replace(df.decimalFormatSymbols.groupingSeparator.toString(), "")
                //text = text?.replace(df.decimalFormatSymbols.decimalSeparator.toString(), "")
                var n = df.parse(text)
                var t = df.format(n)
                val cp = amountEt?.selectionStart
                amountEt?.setText(t)
                endlen = amountEt?.text!!.length
                val sel = cp!!.plus(endlen - inilen)
                if (sel > 0 && sel <= amountEt?.text!!.length) {
                    amountEt?.setSelection(sel)
                } else {
                    // place cursor at the end?
                    amountEt?.setSelection(amountEt?.text!!.length - 1)
                }
            } catch (e: Exception) {
                Log.d("ERROR", e.stackTrace.toString())
            }

            amountEt?.addTextChangedListener(this)
        }

My problem is that the user would like to write into the amountEt (this is an EditText) for example this: 1.02

But when the user write the zero into my edittext, the df.format(n) line result will be 1.

How can I solve this?

UPDATE: I debugged my code and if I write 7.0 into the edittext I got this:

text = "7.0"

n = 7 (type is Number)

If I change this line:

var n = df.parse(text)

to this:

var n = df.parse(text).toDouble()

n = 7.0

t = "7."

Here is an image about my debugger: enter image description here

Upvotes: 1

Views: 4373

Answers (3)

Ruslana R.
Ruslana R.

Reputation: 41

Try to use DecimalFormat("#,###.00") instead of DecimalFormat("#,###.##")

Upvotes: 2

Volkan Sonmez
Volkan Sonmez

Reputation: 785

You can use this code for convert to double

public static double Round(double value, int places) {
        if (places < 0) throw new IllegalArgumentException();
        long factor = (long) Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double) tmp / factor;
    }

Upvotes: 1

Bhavesh Vadalia
Bhavesh Vadalia

Reputation: 814

Hello Please check below code for decimal format

public static String roundTwoDecimalsString(double d) {
        /*DecimalFormat twoDForm = new DecimalFormat("#.##");*/
        DecimalFormat df = new DecimalFormat("#.##");
        String formatted = df.format(d);
        return formatted;
    }

Upvotes: 0

Related Questions