Skip to content

JavaScript validate float number | HTML code example

  • by

You can validate the float number in JavaScript using regular expression (Regex). And another way is doing division by 1 with condition statements.

How do I check that a number is a float or integer?

1.25 --> float  
1 --> integer  
0 --> integer  
0.25 --> float

check for a remainder when dividing by 1:

See below complete example code to test number need two functions.

<html>
   <body>
      <script>
        function isInt(n){
    		return Number(n) === n && n % 1 === 0;
		}

		function isFloat(n){
   			return Number(n) === n && n % 1 !== 0;
		}
         console.log(isInt(100));
         console.log(isFloat(100));

      </script>
   </body>
</html>

Output:

check that a number is float or integer

Or You can use a simple regular expression:

function isInt(value) {

    var er = /^-?[0-9]+$/;

    return er.test(value);
}

How to Check the Validation for floating-point numbers in HTML?

Answer: Here is complete HTML code example to Validation for floating point numbers in JavaScript:-

<html>  
<head>  
    <title>Sample Code</title>  
    <script type="text/javascript">  
    function  CheckFloatingPoint(ValueNumeric)  
    {  
        var objRegex = /(^-?\d\d*\.\d\d*$)|(^-?\.\d\d*$)/;  
  
        //check for numeric characters  
        if(objRegex.test(ValueNumeric))  
        {  
            alert("Is Float number.");  
        }  
        else  
        {  
            alert("Is Not Float number.");  
        }  
    }  
    </script>  
</head>  
    <body>  
    <FORM name="windowEvent">  
        Number : <input type="text" name="txtnumber" />  
        <input type="button" value="Check" name="btnCheckFloatingPoint" onClick="CheckFloatingPoint(txtnumber.value)" />  
    </FORM>  
    </body>  
</html>

Output:

Validation for floating point numbers in HTML

Do comment if you have any questions and doubts on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading