首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android EditText 限制輸入兩位小數:DecimalFormat 與 TextWatcher 實作

     編輯:程式設計綜合問答

簡單格式化顯示

DecimalFormat df = new DecimalFormat("##.##"); // 最多兩位小數,不強制補零
String formatted = df.format(22.123); // "22.12"
editText.setText(formatted);

即時輸入限制

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) {}
    @Override
    public void afterTextChanged(Editable s) {
        String input = s.toString();
        if (input.isEmpty()) return;
        // 允許負號、數字、單一小數點
        if (!input.matches("-?\\d*\\.?\\d{0,2}")) {
            // 移除最後一個非法字元
            s.delete(s.length() - 1, s.length());
        }
    }
});

進階:自訂 InputFilter

editText.setFilters(new InputFilter[] { (source, start, end, dest, dstart, dend) -> {
    String result = dest.toString() + source.subSequence(start, end);
    if (result.matches("-?\\d*\\.?\\d{0,2}")) return null; // 允許
    return ""; // 攔截
}});

注意事項

  • DecimalFormat 四捨五入行為:22.126 → 22.13;若需截斷改用 BigDecimal。
  • 貨幣顯示建議用 NumberFormat.getCurrencyInstance(),自動處理符號、分組。
  • 輸入型別設為 android:inputType="numberDecimal|numberSigned" 呼叫數字鍵盤。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved