[thelist] javascript numbers with decimals
Ken Snyder
kendsnyder at gmail.com
Wed May 7 09:37:56 CDT 2008
Joshua Olson wrote:
>> Since you can enter in 544.44.44 with this, I might also have
>> a isNaN
>> check afterwards. dunno if that is the best tactic, but clearly I
>> don't do a ton of work in js.
>
> This is the crux. We need a well designed regex if we really want to ensure
> our input is good. Sometimes it's better to check to see if the input
> matches the format of what we expect, and then allow the user to fix the
> information instead of trying to manipulate the provided information until
> it matches what we expect (as the original code does).
Forget the regex--why not just compare the float-cast version to the
string version?
function isValidNumber(str) {
return parseFloat(str) == str;
}
isValidNumber('521.44'); // true
isValidNumber(521.44); // true
isValidNumber('.44'); // true
isValidNumber('521.4'); // true
isValidNumber('$521'); // false
isValidNumber('52o'); // false
isValidNumber('544.44.44'); // false
- Ken Snyder
More information about the thelist
mailing list