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:
This can be useful when one must ensure that a string contains an actual floating-point number and nothing else.
The MDN page gives the following examples, all of which return 3.14:
parseFloat("3.14"); parseFloat("314e-2"); parseFloat("0.0314E+2"); parseFloat("3.14more non-digit characters");
The last example contains a string that is clearly not a valid number.