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

Kotlin中如何根据EditText输入的小数位数自动调整DecimalFormat格式化规则

动态适配输入小数位数的DecimalFormat实现方案

核心实现逻辑

  • 监听EditText的实时输入内容,提取小数点后的有效位数
  • 根据提取到的小数位数动态生成对应格式的DecimalFormat模板
  • 格式化输入数值后输出到TextView,同时保留千位分隔符格式

完整代码实现(Java)

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(s)) {
            textView.setText("");
            return;
        }
        String input = s.toString();
        int decimalDigitCount = 0;
        // 计算小数点后的有效位数
        if (input.contains(".")) {
            int dotPosition = input.indexOf(".");
            decimalDigitCount = input.length() - dotPosition - 1;
        }
        // 生成动态格式化模板
        StringBuilder patternBuilder = new StringBuilder("#,###");
        if (decimalDigitCount > 0) {
            patternBuilder.append(".");
            for (int i = 0; i < decimalDigitCount; i++) {
                patternBuilder.append("#");
            }
        }
        DecimalFormat dynamicFormat = new DecimalFormat(patternBuilder.toString());
        // 处理输入异常
        try {
            double inputValue = Double.parseDouble(input);
            textView.setText(dynamicFormat.format(inputValue));
        } catch (NumberFormatException e) {
            // 输入非合法数值时按需处理,此处默认清空输出
            textView.setText("");
        }
    }

    @Override
    public void afterTextChanged(Editable s) {}
});

边界场景适配说明

  • 输入内容末尾为.时,不会额外展示小数点,避免格式异常
  • 可通过添加decimalDigitCount = Math.min(decimalDigitCount, 最大限制位数)的逻辑,控制允许的最大小数位数,避免精度溢出
  • 如果需要保留末尾的0,可将模板中的#替换为0即可

内容的提问来源于stack exchange,提问作者H.Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:24:01