【问题标题】:Format a number string into 2 decimal double independent of the number string length将数字字符串格式化为 2 个十进制双精度数,与数字字符串长度无关
【发布时间】:2020-12-23 01:03:54
【问题描述】:

在使用 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?, start: Int, count: Int, after: Int) {
        print("beforeTextChanged")
  }

  override fun onTextChanged(s: CharSequence?, start: Int, 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")
  }
    
  })

这也失败了。

【问题讨论】:

  • deliveryTipValueeditTextField 不同吗?
  • 用正确的名称更新了问题。谢谢

标签: android kotlin decimalformat android-textwatcher addtextchangedlistener


【解决方案1】:

我认为主要问题是您将文本设置为 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?, start: Int, 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")
    }
})

【讨论】:

    【解决方案2】:

    对于 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

    的结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-25
      • 2012-08-25
      • 1970-01-01
      • 2020-02-04
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多