views:

88

answers:

3

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?

+11  A: 

Use this instead:

var num = Number(value);

Then you can do:

if (isNaN(num)) {
    // take proper action
}
dcp
This is a better idea than my answer :)
thenduks
That's perfect, thanks. I'll have to wait 8 minutes to mark the answer yet :)
mcm69
Just be careful about some specific cases, e.g.: `isNaN(parseFloat("")); // true` and `Number("") == 0; // true`
CMS
@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
@exoboy - I'm not sure I understand, when I run your example I get NaN for num, which is what I would expect since ")(*(*). Anyway, no need to get hostile here.
dcp
@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.
thenduks
thenduks
+4  A: 

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

thenduks
+1 for providing an answer that solves the problem and then pointing the OP to use an answer you consider better.
SB
It's indeed a bad way to solve this problem since it won't work with value like "12.5000".
HoLyVieR
@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.
thenduks
A: 
var asFloat = parseFloat("12aa");
if (String(asFloat).length != "12aa".length) {
     // The value is not completely a float
}
else {
     // The value is a float
}
SimpleCoder