473,769 Members | 5,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 23293
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.demo n.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.demo n.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.meganewss ervers.com
, dated Wed, 9 Feb 2005 19:45:20, seen in news:comp.lang. javascript,

Douglas Crockford <no****@covad.n et> 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.demo n.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.meganewss ervers.com
, dated Wed, 9 Feb 2005 19:45:20, seen in news:comp.lang. javascript,


Douglas Crockford <no****@covad.n et> 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...everyti me...

if(typeof docoument.myFor m.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...everyti me...

if(typeof docoument.myFor m.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">Ple ase 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$6 l.201761@pd7tw2 no>, dated Mon, 14 Feb
2005 07:34:34, seen in news:comp.lang. javascript, Randell D. <reply.via.
ne************* *******@fiproje cts.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.demo n.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.v alue)
or /^\d{1,3}$/.test(control.v alue)

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...everyt ime...

if(typeof docoument.myFor m.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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9
Dr John Stockton wrote:
JRS: In article <ewYPd.385966$6 l.201761@pd7tw2 no>, dated Mon, 14 Feb
2005 07:34:34, seen in news:comp.lang. javascript, Randell D. <reply.via.
ne************* *******@fiproje cts.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.demo n.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.v alue)
or /^\d{1,3}$/.test(control.v alue)
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...every time...

if(typeof docoument.myFor m.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

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

Similar topics

0
4302
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 code everytime I found more than one method to perform a single task. I timed each method to find which would complete faster. I thought I'd share my most recent results which (I believe) should help those write their programs to be more...
4
2304
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
2299
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: *** Invalid arguments to divll. at test_eng/Testout.pm line 30. ...propagated at t/polyser.t line 9. t/polyser.....dubious
10
2334
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: pi = 3.14159... mynum = 3.14226... The mynum is accurate to 2 decimal places compared to pi. I could figure this out easy with a char array since I could just take a character one at a time from each array and compare it. However with a...
20
3720
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 MyVariant = 2 Then MsgBox "MyVariant also equals the value 2" 160 If MyVariant = "" Then HowManyCopies = 1 170 If Not IsNumeric(MyVariant) Then HowManyCopies = 1 MsgBox "OK. HowManyCopies has a value of " & CStr(HowManyCopies) 180 For i =...
8
2842
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. However, when I try to use the variable in the Where clause, either an error occurs or no rows are returned. Any thoughts greatly appreciated! I am using php-4.4.2 and MySQL-4.1.18-0 on Suse 9.1 Jerry
27
10126
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 string in program works ok, but, if I use string from require file I can not seem to insert string. $cccb_id is sting..... to be inserted into $query4 and changes depending on user input.
176
8463
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 their own unit test framework, and then in a lab session see if I can get them to write their own. To give them an example I've created the following UTF class (with a simple test program following). I would welcome and suggestions on how anybody...
13
2412
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 meaning. How can I test for this in the constructor without having to traverse the entire array and checking to make sure the keys are numeric and sequential? Daniel Klein Cuyahoga Falls, OH
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10216
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10049
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8873
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.