Android DecimalFormat格式不正确

我在TextWatcher使用DecimalFormatTextWatcher是我的代码:

 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 (这是一个EditText)例如这个: 1.02

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

我该如何解决这个问题?

更新:我调试我的代码,如果我写入到edittext 7.0我得到这个:

text =“7.0”

n = 7 (类型是数字)

如果我改变这一行:

 var n = df.parse(text) 

对此:

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

n = 7.0

t =“7”。

这是关于我的调试器的图像: 在这里输入图像描述

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

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

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

如果不使用用户定义的模式,可以使用NumberFormat的工厂方法。 我把代码打包成更多的Kotlin-idomatic。

 with(NumberFormat.getNumberInstance(Locale.US)) { maximumFractionDigits = 2 minimumFractionDigits = 1 val n = parse("7.") println(n) println(format(n)) } 

在这个例子中它将打印“7.0”。