473,320 Members | 1,853 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How to test if a variable is numeric?


Folks,

I have a box that expects numeric input - I'd like to test for it (yeah,
I'll have service side checks too but also want client checks).

How can I test that my input is numeric - and numeric could mean
positive or negative floating numbers

For example: return true for 1, 1.5, -1, -4.25 and return false for any
other non-numeric input...

Thanks
Randell D.
Jul 23 '05 #1
10 23252
Randell D. wrote:

Folks,

I have a box that expects numeric input - I'd like to test for it (yeah,
I'll have service side checks too but also want client checks).

How can I test that my input is numeric - and numeric could mean
positive or negative floating numbers

For example: return true for 1, 1.5, -1, -4.25 and return false for any
other non-numeric input...

Thanks
Randell D.


I think you'll find whatever you want here:

<URL:http://www.merlyn.demon.co.uk/js-valid.htm#Val>
--
Rob
Jul 23 '05 #2
> For example: return true for 1, 1.5, -1, -4.25 and return false for any
other non-numeric input...


typeof value == 'number'

is good if you are not worried about NaN or Infinity. If you are, then

typeof value == 'number' && isFinite(value)

is better.

http://www.crockford.com/javascript/remedial.html
Jul 23 '05 #3
Douglas Crockford wrote:
For example: return true for 1, 1.5, -1, -4.25 and return false for
any other non-numeric input...

typeof value == 'number'

is good if you are not worried about NaN or Infinity. If you are, then

typeof value == 'number' && isFinite(value)

is better.

http://www.crockford.com/javascript/remedial.html


Thanks - I found reference of typeof but wasn't quite sure how to use it...

Cheers
randell d.
Jul 23 '05 #4
RobG wrote:
Randell D. wrote:

Folks,

I have a box that expects numeric input - I'd like to test for it
(yeah, I'll have service side checks too but also want client checks).

How can I test that my input is numeric - and numeric could mean
positive or negative floating numbers

For example: return true for 1, 1.5, -1, -4.25 and return false for
any other non-numeric input...

Thanks
Randell D.

I think you'll find whatever you want here:

<URL:http://www.merlyn.demon.co.uk/js-valid.htm#Val>


Thanks... I've had a quick look - but because its bedtime for me now I
think I'll check it out tomorrow morning... I've got about six months of
javascript so given a rough direction I more often than not find my way
- I'm sure what you've provided will prove useful.

Cheers
Randell D.

Jul 23 '05 #5
JRS: In article <74**************************@msgid.meganewsserver s.com
, dated Wed, 9 Feb 2005 19:45:20, seen in news:comp.lang.javascript,

Douglas Crockford <no****@covad.net> posted :
For example: return true for 1, 1.5, -1, -4.25 and return false for any
other non-numeric input...


typeof value == 'number'

is good if you are not worried about NaN or Infinity. If you are, then

typeof value == 'number' && isFinite(value)

is better.


That will do for testing the nature of the entity provided as a function
parameter, for example; but ISTM that the OP has a control whose .value
is of type string, and wants to know whether that string looks line a
number.

The OP did not say whether numbers such as 4.5e3 should be accepted,
meaning 4500, or as 0xc meaning 12 (a true programmer always shops in
Hexadecimal).

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - FAQqish topics, acronyms & links;
some Astro stuff via astro.htm, gravity0.htm ; quotings.htm, pascal.htm, etc.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
Jul 23 '05 #6
Dr John Stockton wrote:
JRS: In article <74**************************@msgid.meganewsserver s.com
, dated Wed, 9 Feb 2005 19:45:20, seen in news:comp.lang.javascript,


Douglas Crockford <no****@covad.net> posted :
For example: return true for 1, 1.5, -1, -4.25 and return false for any
other non-numeric input...


typeof value == 'number'

is good if you are not worried about NaN or Infinity. If you are, then

typeof value == 'number' && isFinite(value)

is better.

That will do for testing the nature of the entity provided as a function
parameter, for example; but ISTM that the OP has a control whose .value
is of type string, and wants to know whether that string looks line a
number.

The OP did not say whether numbers such as 4.5e3 should be accepted,
meaning 4500, or as 0xc meaning 12 (a true programmer always shops in
Hexadecimal).


Fair point and it brings me back to this post because roughly speaking
you've discovered why I have found the above solution doesn't work for me.

The values I'm talking about will not contain alphabetic characters -
thus numbers of 4.5e3 would not be expected but 4500 might be a possibility.

Where I have a form called myForm, and an input tag named myAge, how
could I test that it is numeric?

Using the above example provided by Douglas (and after reading the url
he gave me) I have found the following conditional statement to return
false...everytime...

if(typeof docoument.myForm.myAge.value == 'number')
{ alert("true"); }
else
{ alert("false"); }

The above is for test/example purpose only... could one of you fine
chaps let me know how I could test properly for this?

Replies via the newsgroup would be greatly appreciated so that all other
interested parties can learn to.

Cheers
Randell D.
Jul 23 '05 #7
Randell D. wrote:
[...]
The values I'm talking about will not contain alphabetic characters -
thus numbers of 4.5e3 would not be expected but 4500 might be a
possibility.

Where I have a form called myForm, and an input tag named myAge, how
could I test that it is numeric?

Using the above example provided by Douglas (and after reading the url
he gave me) I have found the following conditional statement to return
false...everytime...

if(typeof docoument.myForm.myAge.value == 'number')
{ alert("true"); }
else
{ alert("false"); }
Because the values of form elements are always passed as
strings. However, JavaScript, being such a friendly language,
type converts where appropriate (or possible it seems to me). So
if the value "2" is entered into your myAge input, the following
will return true:

if (...myAge.value == '2' && ...myAge.value == 2)

The above is for test/example purpose only... could one of you fine
chaps let me know how I could test properly for this?
The best (only?) solution is to specify in your page the format
that you will accept and test for it. For age, I would expect
only a positive integer value, so something like:

<label for="myAge">Please enter your age at last
birthday:<input type="text" id="myAge"></label>

and perhaps a similar field for months if that level of accuracy
is required. Alternatively, ask for birth date (don't get
'them' started on dates). Some may claim even using the word
"birthday" is culturally insensitive for those who do not
recognise such things.

Based on the above, refuse any input that didn't pass being
tested for an optional sign "+" and only numbers. That may
tempt the more cantankerous twenty somethings to attempt say
0.028e3, but it's your form and you get to say what they can put
in it.

var a = ...myAge.value;
alert('Happy: ' + /^\s*[+]?\d+\s*$/.test(a));

which will allow leading & trailing space, optional leading "+"
and digits 0-9 and nothing else (lightly tested).

Replies via the newsgroup would be greatly appreciated so that all other
interested parties can learn to.


But of course.
--
Rob
Jul 23 '05 #8
JRS: In article <ewYPd.385966$6l.201761@pd7tw2no>, dated Mon, 14 Feb
2005 07:34:34, seen in news:comp.lang.javascript, Randell D. <reply.via.
ne********************@fiprojects.moc> posted :
Dr John Stockton wrote:
That will do for testing the nature of the entity provided as a function
parameter, for example; but ISTM that the OP has a control whose .value
is of type string, and wants to know whether that string looks line a
number.

Where I have a form called myForm, and an input tag named myAge, how
could I test that it is numeric?
Read <URL:http://www.merlyn.demon.co.uk/js-valid.htm>; and decide what
you mean by "numeric".

If you want an age in integer years, test with
/^\d+$/.test(control.value)
or /^\d{1,3}$/.test(control.value)

Using the above example provided by Douglas (and after reading the url
he gave me) I have found the following conditional statement to return
false...everytime...

if(typeof docoument.myForm.myAge.value == 'number')
{ alert("true"); }
else
{ alert("false"); }


Yes; something.value is generally of type string, not of type number,
unless you have put a number in it "from inside".

Try alert( typeof document.myForm.myAge.value )

And, if possible, copy'n'paste code; re-typing gives typos.
<FAQENTRY> The string 'valid' appears absent; it would be a good term to
search for, otherwise </FAQENTRY>.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9
Dr John Stockton wrote:
JRS: In article <ewYPd.385966$6l.201761@pd7tw2no>, dated Mon, 14 Feb
2005 07:34:34, seen in news:comp.lang.javascript, Randell D. <reply.via.
ne********************@fiprojects.moc> posted :
Dr John Stockton wrote:


That will do for testing the nature of the entity provided as a function
parameter, for example; but ISTM that the OP has a control whose .value
is of type string, and wants to know whether that string looks line a
number.


Where I have a form called myForm, and an input tag named myAge, how
could I test that it is numeric?

Read <URL:http://www.merlyn.demon.co.uk/js-valid.htm>; and decide what
you mean by "numeric".

If you want an age in integer years, test with
/^\d+$/.test(control.value)
or /^\d{1,3}$/.test(control.value)
Using the above example provided by Douglas (and after reading the url
he gave me) I have found the following conditional statement to return
false...everytime...

if(typeof docoument.myForm.myAge.value == 'number')
{ alert("true"); }
else
{ alert("false"); }

Yes; something.value is generally of type string, not of type number,
unless you have put a number in it "from inside".

Try alert( typeof document.myForm.myAge.value )

And, if possible, copy'n'paste code; re-typing gives typos.
<FAQENTRY> The string 'valid' appears absent; it would be a good term to
search for, otherwise </FAQENTRY>.


Thanks - the URL you quoted, which at first proved frightening actually
helped me - I didn't realise that one could quote a regexp like you have
in some of your examples... I come from a unix background so I actually
know what they are doing (because of having some experience with sed,
awk, grep)...

Thanks for that... it should do the trick,

Randell D.
Jul 23 '05 #10
JRS: In article <42108805$0$30004$5a62ac22@per-qv1-newsreader-
01.iinet.net.au>, dated Mon, 14 Feb 2005 21:12:48, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auau> posted :
Based on the above, refuse any input that didn't pass being
tested for an optional sign "+" and only numbers. That may
tempt the more cantankerous twenty somethings to attempt say
0.028e3, but it's your form and you get to say what they can put
in it.


But 0.028e3 is certainly a number. You mean "... and only digits"
(decimal digits, to be precise).

--
© John Stockton, Surrey, UK. *@merlyn.demon.co.uk / ??*********@physics.org ©
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Correct <= 4-line sig. separator as above, a line precisely "-- " (SoRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SoRFC1036)
Jul 23 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Randell D. | last post by:
Folks, Ever since reading an interesting article in Linux Format on PHP whereby suggested code writing was made that could enhance performance on a server, I've started testing various bits of...
4
by: Cyrus D. | last post by:
Hi guys, What's the best way to test for an empty form value ? I am doing it like this now: $test = $_POST; if(strlen($test) < 1) // it is empty ! Maybe I can just go:
0
by: Jussi Mononen | last post by:
Hi, I'm having problems to successfully execute the test scripts on a Compaq host ( OSF1 tr51bdev V5.1 2650 alpha ). Almost all tests end up with the following error message "PARI: *** ...
10
by: David Casey | last post by:
I'm working on a program for my C++ class and have it all written and working except for one part. I need to compare two numeric variables to determine decimal accuracy between them. For example:...
20
by: MLH | last post by:
120 MyString = "How many copies of each letter do you need?" 150 MyVariant = InputBox(MyString, "How Many?", "3") If MyVariant = "2" Then MsgBox "MyVariant equals the string '2'" If...
8
by: Jerry | last post by:
I am a MySQL and PHP newbie. I am having trouble getting the $w variable in my code below passed to mysql. When I use the value of $w directly in the Where clause, the correct rows are returned....
27
by: user | last post by:
Have require file with several query stings in it. Depending on user input one of strings is selected. Everything going along smoothly until I wanted to also input a variable in string. If I put...
176
by: nw | last post by:
Hi, I previously asked for suggestions on teaching testing in C++. Based on some of the replies I received I decided that best way to proceed would be to teach the students how they might write...
13
by: Daniel Klein | last post by:
I have a class constructor that accepts an array as the only argument. The catch is that the array MUST be an 'integer-indexed' array, not an 'associative' array, because the index position has...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.