13

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?

mcm69
  • 670
  • 6
  • 14

3 Answers3

22

Use this instead:

var num = Number(value);

Then you can do:

if (isNaN(num)) {
    // take proper action
}
dcp
  • 54,410
  • 22
  • 144
  • 164
  • 2
    This is a better idea than my answer :) – rfunduk Jul 15 '10 at 15:30
  • That's perfect, thanks. I'll have to wait 8 minutes to mark the answer yet :) – mcm69 Jul 15 '10 at 15:35
  • 2
    Just be careful about some specific cases, e.g.: `isNaN(parseFloat("")); // true` and `Number("") == 0; // true` – Christian C. Salvadó Jul 15 '10 at 15:38
  • 1
    @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
  • 1
    @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
  • 1
    @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
  • @exoboy: Yes, I do. Do you? "1.23" -> 1.23 = conversion. "kdfj*&$1.23jk" -> 1.23 = coercion. The OP wanted conversion, your answer supplied coercion. Anyway, the votes speak for themselves, as dcp said, no need to get hostile. – rfunduk Jul 15 '10 at 21:27
4

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 :)

rfunduk
  • 30,053
  • 5
  • 59
  • 54
  • 4
    +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
0
var asFloat = parseFloat("12aa");
if (String(asFloat).length != "12aa".length) {
     // The value is not completely a float
}
else {
     // The value is a float
}
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134