1

I've got an app that users input coordinates into.

In the DB and most mapping software they use the decimal notation for lat/lng (eg. 123.1234) rather than the older format: 34N 40' 50.12"

I need to test that a value input into a form is a float, and not a string. But using parseFloat on 34N 40' 50.12" returns 34-- which validates using most tests.

Here's what I'm trying, which is a mashup of a few really clever solutions found here-- but so far I can't get the thing to work properly for all cases. The basic cases I'm testing for are:

  • 123.1234 -- valid
  • '123.1234' -- valid
  • 34N 40' 50.12" -- invalid
  • '34N 40' 50.12"' -- invalid
  • 123 --valid
  • '123' -- valid

Here's a jsfiddle of what I've been trying: http://jsfiddle.net/zfwAj/

3
  • 3
    isNaN should work to filter out those ones: jsfiddle.net/QYMRe Commented Nov 29, 2012 at 22:56
  • @JosephMarikle You should add that as an answer, it's the most simple way to test that. Commented Nov 29, 2012 at 23:16
  • @JosephMarikle Agree. Put it up and I will upvote :) Commented Nov 29, 2012 at 23:20

3 Answers 3

3

Seems I should have posted as an answer

isNaN() should work to filter out those ones jsfiddle.net/QYMRe

Sign up to request clarification or add additional context in comments.

2 Comments

@Joseph-- simple, and elegant-- exactly what I was looking for! Thanks.
@Bruno You're welcome. :) Glad I could help (lol i commented on the wrong spot... it's late)
0

Try

/^\d+\.?\d*$/.test( str );

Fiddle here

2 Comments

/\D/.test('123.45') // true
@Jack Thank you. came up with a different expression :)
0

I suggest this one:

/^-?(\d*\.\d+|\d+(\.\d+)?)$/.test(str)

This accepts negative numbers, and float like (.42)

Fiddle test

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.