I'm using this regex to validate float numbers:
var reg = /\d+\.?\d+/;
But it's validating this as true:
"11.34x"
"11.34abs"
"1a1.34abs"
The \d should only match numbers. What is happening?
If you don't anchor the regular expression, it will match a string that contains a substring that matches.
Try:
var reg = /^\d+\.?\d+$/;
The ^ matches the start of the test string, and $ matches the end. Thus that regular expression will only match strings that have nothing but digits and at most one ".".
edit — as pointed out, your use of the + quantifier means your regex requires digits; if there's a decimal point, then it requires digits on both sides. Maybe that's what you want, maybe it isn't.
0-9parseFloat(n) === +n but only if the OP wants to check all number types, not only floats (considering his ? in regex).Consider using the Number wrapper/constructor function instead:
Number('11.34'); // => 11.34
Number('11.34x'); // => NaN
[Edit] As commenter @VisioN points out, that function has an edge case for empty and pure-whitespace strings, so maybe create a wrapper function:
function reallyParseFloatingPointNumber(s) {
var s = (''+s).trim();
return (s==='') ? NaN : Number(s);
}
\.?means that it might be an integer value as well (though with minimum of 2 digits).-1e-10?