簡單格式化顯示
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" 呼叫數字鍵盤。