You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何为EditText设置带千分位的Double数字格式

实现EditText数字千分位格式化并转为Double类型

1. 实时格式化输入内容

给EditText添加TextWatcher,在用户输入时自动插入千分位逗号,同时避免格式化操作循环触发:

val targetEditText = edt_amount_layout_2
targetEditText.addTextChangedListener(object : TextWatcher {
    private var isFormatting = false // 标记是否正在格式化,防止循环触发

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

    override fun afterTextChanged(s: Editable?) {
        if (isFormatting) return
        isFormatting = true

        // 清除原有逗号,拿到纯数字字符串
        val cleanInput = s.toString().replace(",", "")
        if (cleanInput.isNotEmpty()) {
            try {
                val number = cleanInput.toDouble()
                // 配置千分位格式化规则,可根据需求调整小数位数
                val formatter = DecimalFormat("#,###.##")
                val formattedText = formatter.format(number)
                // 设置格式化后文本,并将光标定位到末尾
                targetEditText.setText(formattedText)
                targetEditText.setSelection(formattedText.length)
            } catch (_: NumberFormatException) {
                // 忽略无效数字输入
            }
        }

        isFormatting = false
    }
})

2. 将格式化文本转为Double类型

由于EditText显示的是带逗号的字符串,直接调用toDouble()会报错,需要先移除逗号再转换:

val inputContent = edt_amount_layout_2.text.toString().replace(",", "")
val amount_loan = if (inputContent.isNotEmpty()) inputContent.toDouble() else 0.0

额外注意事项

  • 建议给EditText设置输入类型限制,避免非数字字符输入:android:inputType="numberDecimal"
  • 如需固定小数位数,可修改DecimalFormat的模式,比如#,###.00表示强制保留两位小数,#,###表示只格式化整数部分
  • 可添加输入合法性判断,比如限制最大最小值,避免转换时出现异常

内容的提问来源于stack exchange,提问作者mahdi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:30:57