Cách chuẩn: Thử parse, bắt NumberFormatException. Ba phương thức đều ném exception này khi thất bại.
3 phương thức parse double
| Phương thức | Trả về | Xử lý null | Trim khoảng trắng |
|---|---|---|---|
Double.parseDouble(String) | primitive double | Ném NullPointerException | Không |
Double.valueOf(String) | Object Double | Ném NullPointerException | Có (tự trim) |
new Double(String) (deprecated Java 9+) | Object Double | Ném NullPointerException | Có |
Pattern an toàn: Try-catch wrapper
public static boolean isParsableToDouble(String str) {
if (str == null) return false;
try {
Double.parseDouble(str.trim()); // hoặc Double.valueOf(str)
return true;
} catch (NumberFormatException e) {
return false;
}
}
Ví dụ tương tác
import java.util.Scanner;
public class DoubleParseCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Nhập chuỗi: ");
String input = sc.nextLine();
try {
double value = Double.parseDouble(input);
System.out.println("✅ Parse thành công: " + value);
} catch (NumberFormatException e) {
System.out.println("❌ Không parse được thành double");
}
}
}
Kết quả
Nhập chuỗi: 2245g
❌ Không parse được thành double
Nhập chuỗi: 3.14159
✅ Parse thành công: 3.14159
Nhập chuỗi: -123.45
✅ Parse thành công: -123.45
Regex validation (không ném exception)
// Regex số thực đơn giản (có dấu, phần thập phân tùy chọn)
String DOUBLE_REGEX = "^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$";
public static boolean isValidDoubleRegex(String s) {
return s != null && s.matches(DOUBLE_REGEX);
}
Khuyến nghị: Dùng try-catch cho code đơn giản, regex cho validation hiệu năng cao/hàng loạt.