Regular Expression for Validating Floating-Point Numbers

This is more of a classroom assignment problem, but it creeps up from time to time in the real world. The best I’ve been able to come up with over the years is:



I was asked why bother with this when JavaScript has a parseFloat() function.

This can be useful when one must ensure that a string contains an actual floating-point number and nothing else.

The JavaScript parseFloat() function will accept any string (including garbage like alphabetic characters) so long as the first sequence of characters is a float.

The MDN page gives the following examples, all of which return 3.14:

parseFloat("3.14more non-digit characters");

The last example contains a string that is clearly not a valid number.

This entry was posted in Programming and tagged , , , , , , . Bookmark the permalink.

One Response to Regular Expression for Validating Floating-Point Numbers

  1. Artem says:

    ^(24[0-9]|1[0-9][0-9]|[4-9][0-9]|[3-9][0-9])\.?[0-9]{0,2}$ 30-249.99 welcome

Leave a Reply