我们如何在 JavaScript 中验证小数?
以下是用于在 JavaScript 中验证小数的代码 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Validate decimal numbers in JavaScript</h1> <div style="color: green;" class="result"></div> <input type="number" class="num" /> <button class="Btn">CHECK</button> <h3>Click the above button to check if a valid decimal number is entered or not</h3> <script> let resEle = document.querySelector(".result"); document.querySelector(".Btn").addEventListener("click", () => { var str = document.querySelector(".num").value; var regex = /^[-+]?[0-9]+\.[0-9]+$/; var match = str.match(regex); if (match) resEle.innerHTML = "The number given is a decimal number"; else resEle.innerHTML = "The number given is not a decimal number"; }); </script> </body> </html>
输出
上述代码将生成以下输出 −
输入一个普通数字并单击“CHECK”按钮 −
输入一个小数并单击“CHECK” −
广告