Jump to content

Valid number?


davej

Recommended Posts

I'm having a problem in Chrome with some navigation values causing exceptions to be thrown when .toFixed is used on them. I am now trying to use...

temp = position.coords....if (temp != null && Number(temp) != NaN)data += temp.toFixed(8);

But this isn't working 100% either, at least not in Firefox. What is the best way to screen for invalid numbers?

Edited by davej
Link to comment
Share on other sites

The point of Number() isn't to validate numbers, but to cast to a number.When casting to number, as long as the first character is numeric it is considered a number and it will continue to parse until it finds a non.numeric character. Now that I think of it, NaN is never equal to another NaN. The only way to check that a "number" is not a number is to use isNaN().

Link to comment
Share on other sites

Why would you reject that if you can just use the number value though?I mean, you can simply do:

x = new Number(x);if (!isNaN(x)) {    //No problem. Continue with "x", that is now surely a valid number.}

Link to comment
Share on other sites

Perhaps it's validation before passing to the server-side. PHP casts to numbers using the same rules as Javascript using (int) or intval(), (float) or floatval()

Link to comment
Share on other sites

If a user entered 5abc you might want to reject it simply because a number was expected and they entered something goofy. I had not thought of using a regex for that purpose. Thanks.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...