admin管理员组

文章数量:1200965

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?

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 asked Jul 15, 2010 at 15:28 mcm69mcm69 7306 silver badges14 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 22

Use this instead:

var num = Number(value);

Then you can do:

if (isNaN(num)) {
    // take proper action
}

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

var asFloat = parseFloat("12aa");
if (String(asFloat).length != "12aa".length) {
     // The value is not completely a float
}
else {
     // The value is a float
}

本文标签: javascriptIs it possible to parseFloat the whole stringStack Overflow