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.

One thought on “Regular Expression for Validating Floating-Point Numbers

Leave a Reply