Validate decimal numbers in JavaScript | Match, and RegEx

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.