Skip to content

Validate decimal numbers in JavaScript | Match, and RegEx

  • by

Use match() method to Validate decimal numbers in JavaScript. Here is example code to validate decimal numbers.

<html>
   <body>
      <script>
         var str = "17";
         var re = /^[-+]?[0-9]+\.[0-9]+$/;
         var found = str.match( re );
         alert("decimal" );
      </script>
   </body>
</html>

Output:

Validate decimal numbers in JavaScript

Regex in JavaScript for validating decimal numbers

Use the following expression as below example code.

<html>
   <body>
      <script>
         var regexp = /^\d+\.\d{0,2}$/;

		// returns true
		var res = regexp.test('10.5')
         alert(res);
      </script>
   </body>
</html>

Output:

Regex in JavaScript for validating decimal numbers

Do comment if you have any questions and suggestions on this topic.

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