ใช้ Regular Expression ตรวจสอบว่าสตริงเป็นเลขทศนิยมที่ถูกต้อง: มีเครื่องหมาย + หรือ - ได้ จำนวนเต็มอย่างน้อย 1 ตัว จุดทศนิยม 1 ตัว และเศษทศนิยมอย่างน้อย 1 ตัว Pattern: /^[-+]?[0-9]+\.[0-9]+$/
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Validate Decimal Number</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>ตรวจสอบเลขทศนิยมใน JavaScript</h1>
<div style="color: green;" class="result"></div>
<input type="text" class="num" placeholder="พิมพ์ตัวเลข" />
<button class="Btn">ตรวจสอบ</button>
<h3>กดปุ่มเพื่อตรวจสอบว่าเป็นเลขทศนิยมที่ถูกต้องหรือไม่</h3>
<script>
const resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
const str = document.querySelector(".num").value;
// [-+]? = เครื่องหมาย + หรือ - ได้ 0 หรือ 1 ครั้ง
// [0-9]+ = ตัวเลข 1 ตัวขึ้นไป
// \. = จุดทศนิยม (escape ด้วย \)
// [0-9]+ = เศษทศนิยม 1 ตัวขึ้นไป
const regex = /^[-+]?[0-9]+\.[0-9]+$/;
const match = str.match(regex);
if (match) {
resEle.textContent = "เป็นเลขทศนิยมที่ถูกต้อง";
resEle.style.color = "green";
} else {
resEle.textContent = "ไม่ใช่เลขทศนิยม (อาจเป็นจำนวนเต็ม, ว่าง, หรือรูปแบบผิด)";
resEle.style.color = "red";
}
});
</script>
</body>
</html>
ผลลัพธ์

กรอกจำนวนเต็ม (เช่น 42) กด "ตรวจสอบ":

กรอกทศนิยม (เช่น 3.14) กด "ตรวจสอบ":

Pattern แบบละเอียด
/^[-+]?[0-9]+\.[0-9]+$/
// ^ เริ่มต้น
// [-+]? เครื่องหมาย + หรือ - (optional)
// [0-9]+ จำนวนเต็ม 1 ตัวขึ้นไป
// \. จุดทศนิยม (ต้อง escape)
// [0-9]+ เศษทศนิยม 1 ตัวขึ้นไป
// $ จบสตริง
รูปแบบอื่นที่นิยมใช้
| Pattern | คำอธิบาย | ตัวอย่างผ่าน | ตัวอย่างไม่ผ่าน |
|---|---|---|---|
/^[-+]?\d*\.\d+$/ | ยอมรับ .5 (ไม่มีจำนวนเต็มหน้าจุด) | .5, 0.5, -3.14 | 5, 5. |
/^[-+]?\d+(\.\d+)?$/ | ยอมรับจำนวนเต็มด้วย (ทศนิยม optional) | 5, 3.14, -2 | 5., .5 |
/^[-+]?(\d+\.\d*|\.\d+)$/ | รองรับทั้ง 5. .5 5.0 (มาตรฐาน) | 5, 5.0, .5, 3.14 | 5., abc |
/^[0-9]*\.?[0-9]+$/ | ไม่มีเครื่องหมาย - ไม่รองรับลบ | 3.14, 42, .5 | -3.14 |
วิธีอื่น: ใช้ Number() + ตรวจสอบ
function isDecimal(str) {
const num = Number(str);
// ตรวจสอบ: เป็นตัวเลข, ไม่ใช่ NaN, ไม่ใช่ Infinity, มีจุดทศนิยม
return !isNaN(num) && isFinite(num) && str.includes(".") && /^[-+]?\d*\.\d+$/.test(str);
}
// หรือ简单:
const isDecimal = (str) => /^[-+]?\d*\.\d+$/.test(str) && !isNaN(str);
⚠️ ข้อควรระวัง
Number("3.14")คืน 3.14 แต่Number("3.")คืน 3 (ไม่ใช่ทศนิยม)parseFloat("3.14abc")คืน 3.14 (ตัดทิ้งตัวอักษรท้าย) — ไม่เหมาะ validation- Regex ต้อง anchor
^$ไม่งั้น "abc3.14def" จะ match - Scientific notation (1e5) ไม่ match pattern นี้ — ต้องใช้ pattern อื่น