有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android DecimalFormat格式不正确

我在TextWatcher中使用DecimalFormat,下面是我的代码:

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)
        }

我的问题是,用户希望写入amountEt(这是一个编辑文本),例如:1.02

但是当用户将zero写入我的编辑文本时,df.format(n)行结果将是1

我怎样才能解决这个问题

更新: 我调试了我的代码,如果我将7.0写入edittext,我会得到以下结果:

text=“7.0”

n=7(类型为数字)

如果我更改此行:

var n = df.parse(text)

为此:

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

n=7.0

t=“7。”

以下是有关我的调试器的图像: enter image description here


共 (3) 个答案

  1. # 1 楼答案

    您好,请检查下面的十进制格式代码

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

    尝试使用DecimalFormat(“#,###.00”)而不是DecimalFormat(“#,###.#”)

  3. # 3 楼答案

    您可以使用此代码将其转换为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;
        }