String s = editText.getText().toString();
double d = Double.parseDouble(s); // s 為空串 "" 直接拋 NumberFormatException
String s = editText.getText().toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(this, "請輸入數值", Toast.LENGTH_SHORT).show();
return;
}
try {
double d = Double.parseDouble(s);
// 計算
} catch (NumberFormatException e) {
Toast.makeText(this, "格式錯誤", Toast.LENGTH_SHORT).show();
}
在 XML 設定 android:inputType="numberDecimal|numberSigned" 限制鍵盤輸入,但仍需後端驗證。