将数字字符串格式化为2个十进制双精度数字,与数字字符串长度无关

问题描述

在使用Kotlin开发的Android应用程序中,有一个EditText仅接受视为美元的数字。输入的格式必须设置为2位小数,以便输入的格式如下所示:

  • 7-> 0.07
  • 73-> 0.73
  • 736-> 7.36

尝试使用输入过滤器。输入过滤器还用于限制最大值和单个十进制输入项。

editTextField.filters =
            arrayOf(DecimalInputFilter())

class DecimalDigitsInputFilter() : InputFilter {
    override fun filter(
    source: CharSequence?,start: Int,end: Int,dest: Spanned?,dstart: Int,dend: Int
    ): CharSequence? {}

}

无法获取格式化的数字。能够根据规则限制输入。

editTextField.addTextChangedListener(object : TextWatcher{
   override fun beforeTextChanged(s: CharSequence?,count: Int,after: Int) {
        print("beforeTextChanged")
  }

  override fun onTextChanged(s: CharSequence?,before: Int,count: Int) {
       print("onTextChanged")
       val inputFormatter = DecimalFormat("0.00")
       inputFormatter.isDecimalSeparatorAlwaysShown = true
       inputFormatter.minimumFractionDigits = 2
       editTextField.setText((s.toString()).format(inputFormatter))
  }

  override fun afterTextChanged(s: Editable?) {
       print("afterTextChanged")
  }
    
  })

这也失败。

解决方法

我认为主要的问题是您正在EditText内的TextWatcher内设置文本,这会导致循环递归,然后导致堆栈溢出。您应该更改在删除并再次添加TextWatcher中包裹的文本。这是一个简单的解决方案:

editTextField.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?,start: Int,count: Int,after: Int) {
        print("beforeTextChanged")
    }

    override fun onTextChanged(s: CharSequence?,before: Int,count: Int) {
        print("onTextChanged")

        val newValue = s.toString()
            .takeIf { it.isNotBlank() }
            ?.replace(".","")
            ?.toDouble() ?: 0.0

        editTextField.let {
            it.removeTextChangedListener(this)
            it.setText(String.format("%.2f",newValue / 100))
            it.setSelection(it.text?.length ?: 0)
            it.addTextChangedListener(this)
        }
    }

    override fun afterTextChanged(s: Editable?) {
        print("afterTextChanged")
    }
})
,

对于Kotlin

 fun roundOffDecimal(number: Double): String? {
        val df = DecimalFormat("#,###,###.##")
        df.roundingMode = RoundingMode.CEILING
        return df.format(number)
    }

RoundingMode.CEILNG或RoundingMode.FLOOR用于四舍五入最后一位数字。

#,###.##

根据所需的位值类型和所需的小数位数定制此部分。

上面的代码将显示与 3,250,250.12

类似的结果

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...