473,811 Members | 3,135 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to tell what a variable is

How can I tell if a variable. I want ot tell whether two variables are:

1. Both numbers. Just a number. same as the number object in
javascript.
2. Either one is a string containing a number. For exmaple a
string like "354" or "295.395".
3. Either are strings containing a fraction. For example a string
like "46/987".
4. Either is a "fraction". By "fraction" I mean that it is either
an array of two numbers or two number strings like in number 2.
The first being the top and the second being the bottom. For
example: [34,78] or ["34","57"].

Jul 23 '05 #1
5 1562
greenflame wrote:
How can I tell if a variable. I want ot tell whether two variables are:

1. Both numbers. Just a number. same as the number object in
javascript.
To see if x is a number:

var x = 5;
if ( 'number' == typeof x ) // true

var x = '5';
if ( 'number' == typeof x ) // false

Note that if your values come from form text elements, they are strings
by default but may be converted to numbers.
2. Either one is a string containing a number. For exmaple a
string like "354" or "295.395".
I think you mean a string that can be converted to a number.

var x = '354';
if ( 'string' == typeof x ) // true

However, this test is a bit useless - a regular expression provides a
better solution:

if ( /^\d+[.]?[\d*]?$/.test(x) ) {

This will return true if x is one or more digits followed by an
optional '.' followed by more optional digits. Anything else will
return false. Note that this will rule out notation like 1.2e34 (which
is otherwise perfectly valid as a number in JavaScript).

Search the news group for examples of regular expression tests for
number formats, there are plenty of examples.
3. Either are strings containing a fraction. For example a string
like "46/987".
var x = '46/987';
if ( /\//.test(x) ) // true - string contains a '/' character

But you probably need to detect that there is only one '/' character
and that the stuff either side is a number.
4. Either is a "fraction". By "fraction" I mean that it is either
an array of two numbers or two number strings like in number 2.
The first being the top and the second being the bottom. For
example: [34,78] or ["34","57"].


var x = '34,78';
if ( /\,/.test(x) ) // true - string contains a ',' character

*Note*
Each of the above represent a trivial cases. There are other tests
that likely should be conducted, such as checking whether the variable
contains only digits, periods or commas, whether it contains multiple
instances of those characters, what is an OK value and what isn't, etc.

It is better to say how you are getting the input and what it is being
used for so that appropriate tests can be suggested.
--
Rob
Jul 23 '05 #2
On 24/06/2005 03:42, RobG wrote:
greenflame wrote:
How can I tell if a variable. I want ot tell whether two variables are:

1. Both numbers. Just a number. same as the number object in
javascript.
Just so you know, number objects are different from number values.

var v = 5, // value
o = new Number(5); // object

You can perform arithmetic with both as the number object will be
type-converted to a number first, but you cannot detect them in the same
way. Rob's suggestion will work for values, whilst

if(o && (Number == o.constructor))

will work for numbers. If you don't actually care about objects, then
never mind...

[snip]
if ( /^\d+[.]?[\d*]?$/.test(x) ) {


That's broken. For properly formatted decimal numbers,

/^[+-]?(0|[1-9]\d*)(\.\d*)?$/

is better.

[snip]
3. Either are strings containing a fraction. For example a string
like "46/987".
Presumably, the numerator and denominator should both be integers, and
the denominator should not be zero?

/^[+-]?(0|[1-9]\d*)\/[1-9]\d*$/
4. Either is a "fraction". By "fraction" I mean that it is either
an array of two numbers or two number strings like in number 2.
The first being the top and the second being the bottom. For
example: [34,78] or ["34","57"].


Though an array would be more convenient, an object would be more
appropriate. You could still use 0 and 1 as indices:

{0 : 34, 1 : 78}

or you could use named properties. If you used a constructor function,
then testing is very simple:

function Fraction(numera tor, denominator) {
this.n = numerator; /* Or this[0] */
this.d = denominator;
}

var myFraction = new Fraction(34, 78);

if(myFraction && (Fraction == myFraction.cons tructor)) {
/* Is a Fraction instance */
}

You could add checks into the constructor to ensure that the arguments
are numbers, or number-like strings if you wanted to.

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
Hmmm... thanks for the help. It seems I should learn about regular
expressions. So what are they? Where can I learn all about them?

Jul 23 '05 #4
Um.... sorry for posting twice but I for got to say somenting... Rob
G.. your last way to check if a variable is of the format [324,72] or
["345","36"] doesnt actually test if it is of this format or atleast it
doesnt seem to they way you made the code. I havent tryed it but it
seems like it would only detect if the contents are of the form
"543,876".

Jul 23 '05 #5
Again sorry for posting what is now three straight posts. I was
wondering like how to tell if a variable is a string and then convert
to number. for example convert :

1. "2" to 2
2. "1.653" to 1.653
3. "1.325e23" to 1.325e23
4. "4.24e-4" to 4.24e-4

I know this was partially covered above. Also I am probably having my
question sort of answered twice.

Jul 23 '05 #6

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

Similar topics

9
2708
by: Harry J. Smith | last post by:
How do you tell if two variables past as arguments to a subroutine are actually the same variable? In some languages you can compare their addresses. Visual Basic doesn't have pointers so what is the best way to do this? Public Sub SetToUI(X As MultiUI, Z As MultiUI) 'Z = X 'MultiUI is a user defined type (Multiple-precision unsigned integer) If Z = X Then Exit Sub ....
10
2082
by: Andreas Sheriff | last post by:
Please evaluate the following snippet: int a=5; int b; b = a++ + a; Edit1->Text = b; a = 5; b = a++ + ++a; Edit2->Text = b;
9
9378
by: Ian Richardson | last post by:
If I follow the steps on http://www.dhtmlcentral.com/tutorials/tutorials.asp?id=11 to add .js files to a document on demand, let's say by <body onload="blah();">, how can I reliably tell that it has been loaded? BTW, I'm doing this for several .js files (and I don't always know how many I'll be loading), so I need to check them all. If I code for IE, I can check all the document.scripts.readyState values (not being "uninitialized" or...
15
2132
by: tabonni | last post by:
I want to check each button groups and save the checked value into a 2 dimensional array. But, it doesn't work. Could anyone tell me what's wrong with my code. My code is as follow: <html> <body> <script language="javascript"> <!-- var temp = new Array(2) var status = new Array();
2
1726
by: sparks | last post by:
ok I was trying to do something real simple I thought Me.Clinic.DefaultValue = Me.Clinic.Value I got error either ! or . misused or not found...something like that I thought ok how can you not find the variable that this field is tied to. ok it takes a variant so maybe its Me.Clinic.DefaultValue = Me..Value no thats not it so I just tried everything then someone said no do
4
1519
by: sueyic | last post by:
Hello, What is the syntax for telling php that a variable is an array, or an array of arrays? Let's say I have $arrTerms /* @param array of arrays $arrTerms */
7
3171
by: icosahedron | last post by:
Is there a way to determine if a parameter to a function is a constant (e.g. 2.0f) versus a variable? Is there some way to determine if this is the case? (Say some metaprogramming tip or type trait?) I have a function with an if statement, that I would like to optimize away somehow. I was hoping the compiler would do it for me, but it doesn't seem to. Jay
6
2219
by: thomas.luce | last post by:
Okay, I have been programming for a long time, and am getting back into C after about a 4 year break from it. Below is some code that won't compile for the life of me, and it is driving me crazy! If anyone can see anything that I can't, I would love to know. All the code is pasted, although in my real code it is broken into a header and a seperate .c file. #include <stdlib.h> typedef enum {typeNum, typeString} VariableType;
7
2479
by: Zhang Weiwu | last post by:
Dear all How does javascript realiablily tell if a variable is a reference to an HTML Element "<select>", without causing browser to pop up error message? if (variable.constructor == HTMLElementSelect) // doesn't work, Firefox complain no such property if variable is undefined if (typeof variable == "object" && variable.constructor == HTMLElementSelect) // doesn't work, IE complain object do not have this property "constructor"
0
9722
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
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10644
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
10379
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
10124
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
6882
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();...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4334
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
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.