Take the 2-minute tour ×

As you know, the javascript's parseFloat function works only until it meets an invalid character, so for example

parseFloat("10.123") = 10.123
parseFloat("12=zzzz") = 12
parseFloat("z12") = NaN

Is there a way or an implementation of parseFloat that would return NaN if the whole string is not a valid float number?

share|improve this question
add comment

3 Answers

up vote 15 down vote accepted

Use this instead:

var num = Number(value);

Then you can do:

if (isNaN(num)) {
    // take proper action
share|improve this answer
This is a better idea than my answer :) –  rfunduk Jul 15 '10 at 15:30
Just be careful about some specific cases, e.g.: isNaN(parseFloat("")); // true and Number("") == 0; // true –  CMS Jul 15 '10 at 15:38
@exoboy - You don't need to deal with illegal characters with this solution. Try this and you'll see: var x = Number("#!"); if (isNaN(x)) alert("bad"); –  dcp Jul 15 '10 at 16:01
@exoboy - I'm not sure I understand, when I run your example I get NaN for num, which is what I would expect since ")(*(*&()*H3.4" isn't a valid float. Also, you left off an else clause before your second alert call, so perhaps you should test your code ;). Anyway, no need to get hostile here. –  dcp Jul 15 '10 at 17:07
@exoboy: Number doesn't 'coerce' a number out of a string. It's a function to convert a string into a number, if it is a valid number. The question asked to only yield a number if the whole string is a valid number. –  rfunduk Jul 15 '10 at 18:05
show 2 more comments

Maybe try:

var f = parseFloat( someStr );
if( f.toString() != someStr ) {
  // string has other stuff besides the number

Update: Don't do this, use @dcp's method :)

share|improve this answer
+1 for providing an answer that solves the problem and then pointing the OP to use an answer you consider better. –  NG. Jul 15 '10 at 15:33
It's indeed a bad way to solve this problem since it won't work with value like "12.5000". –  HoLyVieR Jul 15 '10 at 16:43
@HoLyVieR: Yea, it really depends on where your data is coming from. Most languages serializing out values wont pad with zeroes unless you explicitly say so. Since Number() solves these sorts of problems (with a few caveats of it's own) there's no need to do this. –  rfunduk Jul 15 '10 at 18:01
add comment
var asFloat = parseFloat("12aa");
if (String(asFloat).length != "12aa".length) {
     // The value is not completely a float
else {
     // The value is a float
share|improve this answer
add comment

Your Answer


