473,699 Members | 2,702 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

isInteger, isFloat functions?

Hello,
Does anyone have handy functions for testing whether a text field value is

a) a valid integer
b) a valid floating point number?

Thanks for any assistance, - Dave
Jul 23 '05 #1
35 32864
D. Alvarado wrote:
Hello,
Does anyone have handy functions for testing whether a text field value is

a) a valid integer
b) a valid floating point number?


Try the FAQ:

http://www.jibbering.com/faq/#FAQ4_12

Follow the links for parseInt and parseFloat - choose your
- poison MS or Netscape. I think the Netscape reference is
better on this one. You may find isNaN useful too.

Cheers, Rob.
Jul 23 '05 #2
Fox


RobG wrote:
D. Alvarado wrote:
Hello,
Does anyone have handy functions for testing whether a text field
value is
a) a valid integer
b) a valid floating point number?

Try the FAQ:

http://www.jibbering.com/faq/#FAQ4_12

Follow the links for parseInt and parseFloat - choose your
- poison MS or Netscape. I think the Netscape reference is
better on this one. You may find isNaN useful too.

Cheers, Rob.


parseInt and parseFloat will both accept non-numeric characters in a string and
return the digits used up to the first non-digit character -- e.g.:

parseInt("123ab c") will return 123 [a "true"]
parseFloat("123 .2abc") will return 123.2 [also a "true"]

technically, you cannot pass either of these to an "isInteger" and "isFloat" and
receive a true -- they should both be false.
Jul 23 '05 #3
Fox


D. Alvarado wrote:
Hello,
Does anyone have handy functions for testing whether a text field value is

a) a valid integer
function
isInteger(s)
{
var n = trim(s);
return n.length > 0 && !(/[^0-9]/).test(n);

}
b) a valid floating point number?


function
isFloat(s)
{
var n = trim(s);
return n.length>0 && !(/[^0-9.]/).test(n) && (/\.\d/).test(n);
}
isFloat "qualifies" and differentiates from an integer by testing for a decimal
point and at least one digit after it. Therefore, 123. will not qualify as a
floating point number [nor an integer in isInteger] -- it is an invalid input.
If you require a digit *before* the decimal point for a float, you'll have to
adjust the regex.

These routines merely test for *any* non-digit(/non-numeric) character
(therefore the 'g' selector in the regex is not required).
[note: empty strings will return a "false positive" - that's why testing for
string length]

To trim away any spaces before or after the string:

function
trim(s)
{
return s.replace(/^\s+|\s+$/g, "");
}
You can test for Integer OR Float with:

function
isNumber(s)
{
var n = trim(s);
return n.length>0 && +n == n;
}

or you can use !isNaN(numstr) on a non-empty string. [!isNaN("") returns true
and isNaN apparently trims strings of whitespace before testing]
Jul 23 '05 #4
D. Alvarado wrote on 20 sep 2004 in comp.lang.javas cript:
Does anyone have handy functions for testing whether a text field
value is

a) a valid integer
t = " -12.345"
alert(!/\./.test(t) && +t==t)
t = " -12345"
alert(!/\./.test(t) && +t==t)
b) a valid floating point number?


t = " -12.34.5"
alert(+t==t)
t = " -12.345"
alert(+t==t)

Shoot!
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress,
but let us keep the discussions in the newsgroup)

Jul 23 '05 #5
On 20/9/04 10:54 am, Evertjan. wrote:
D. Alvarado wrote on 20 sep 2004 in comp.lang.javas cript:
Does anyone have handy functions for testing whether a text field
value is

a) a valid integer


t = " -12.345"
alert(!/\./.test(t) && +t==t)
t = " -12345"
alert(!/\./.test(t) && +t==t)
b) a valid floating point number?


t = " -12.34.5"
alert(+t==t)
t = " -12.345"
alert(+t==t)

Shoot!


<pedant>
what about t = "1.2e+03"?
</pedant>

--
Philip Ronan
ph***********@v irgin.net
(Please remove the "z"s if replying by email)
Jul 23 '05 #6
Philip Ronan wrote on 20 sep 2004 in comp.lang.javas cript:
On 20/9/04 10:54 am, Evertjan. wrote:
a) a valid integer
t = " -12.345"
alert(!/\./.test(t) && +t==t)
t = " -12345"
alert(!/\./.test(t) && +t==t)

[..]
<pedant>
what about t = "1.2e+03"?
</pedant>


t = "1.2e+03"
alert(!/\./.test(+t) && +t==t)
t = "5.0000"
alert(!/\./.test(+t) && +t==t)

will take care of those.

However, it will miserably fail here:

t = "1.2e+33"
alert(!/\./.test(+t) && +t==t)

Though technically incorrect [John?],
are such big/small numbers important to the OP ?
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress,
but let us keep the discussions in the newsgroup)

Jul 23 '05 #7
On 20/9/04 11:15 am, Evertjan. wrote:
t = "1.2e+03"
alert(!/\./.test(+t) && +t==t)
t = "5.0000"
alert(!/\./.test(+t) && +t==t)

will take care of those.

However, it will miserably fail here:

t = "1.2e+33"
alert(!/\./.test(+t) && +t==t)


It will also fail when t = infinity (e.g., "t=1/0")

How about:

alert(!/\./.test(+t) && +t==t && (t+1)!=t)

--
Philip Ronan
ph***********@v irgin.net
(Please remove the "z"s if replying by email)
Jul 23 '05 #8
Fox wrote:

technically, you cannot pass either of these to an "isInteger" and
"isFloat" and receive a true -- they should both be false.


I think Rob is on the right track (but could have offered some
code...)

Testing strings using regular expressions to see if they have
decimal places (and how many), surplus characters, scientific
notation, etc. requires exhaustive testing... let JS do
the work.

How about:

var x = someValue;
if (x == parseInt(x) && x == parseFloat(x)) {
alert(x + ' is a int');
} else if (x == parseFloat(x)) {
alert(x + ' is a float');
} else {
alert(x + ' is not a number I like...');
}

You can even use scientific notation if you like, so 1.2e+03 is
recognised as a float quite happily without complex pattern
matching.

Cheers, Fred
Jul 23 '05 #9
Philip Ronan wrote on 20 sep 2004 in comp.lang.javas cript:
It will also fail when t = infinity (e.g., "t=1/0")

How about:

alert(!/\./.test(+t) && +t==t && (t+1)!=t)


I don't think infinity is an integer but I wouldn't mind if it is.

(+t+1)!=+t ?

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress,
but let us keep the discussions in the newsgroup)

Jul 23 '05 #10

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

Similar topics

5
3340
by: hokiegal99 | last post by:
A few questions about the following code. How would I "wrap" this in a function, and do I need to? Also, how can I make the code smart enough to realize that when a file has 2 or more bad charcters in it, that the code needs to run until all bad characters are gone? For example, if a file has the name "<bad*mac\file" the program has to run 3 times to get all three bad chars out of the file name. The passes look like this:
99
5892
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less important changes, so in this thread I would like to focus on that issue alone. I have edited the Proposed Syntax example below to take out the changes unecessary to this discussion. I left in the change of "instance variable" syntax (...
1
741
by: Bob Rock | last post by:
Hello, in the last few days I've made my first few attempts at creating mixed C++ managed-unmanaged assemblies and looking aftwerwards with ILDASM at what is visible in those assemblies from a managed point-of-view I've noticed that: 1) for each managed and unmanaged C function (not C++ classes) I get a public managed static method (defined on a 'Global Functions' class) in the generated assembly with an export name of the form...
47
3865
by: Richard Hayden | last post by:
Hi, I have the following code: /******************************** file1.c #include <iostream> extern void dummy(); inline int testfunc() {
21
746
by: Rubén Campos | last post by:
I haven't found any previous message related to what I'm going to ask here, but accept my anticipated excuses if I'm wrong. I want to ask about the real usefulness of the 'inline' keyword. I've read many authors (and it's my belief, too) who discourage the use of the 'inline' keyword, because: - The 'inline' word only advice the compiler about wich functions should be expanded, but not force it to expand them. Also, the compiler can...
25
5414
by: Stijn Oude Brunink | last post by:
Hello, I have the following trade off to make: A base class with 2 virtual functions would be realy helpfull for the problem I'm working on. Still though the functions that my program will use a lot are the ones that are virtual and thus will slow down the calculation, at least that is what what I have read on several places on the internet. It makes sense the program has to work with some kind off lookup table for the virtual...
2
6528
by: Koen | last post by:
Hi all, I have a question about something rather common, but I'm a bit lost at the moment: Lat's say you have this: // in A.h Class A {
17
3621
by: cwdjrxyz | last post by:
Javascript has a very small math function list. However there is no reason that this list can not be extended greatly. Speed is not an issue, unless you nest complicated calculations several levels deep. In that case you need much more ram than a PC has to store functions calculated in loops so that you do not have to recalculate every time you cycle through the nest of loops. Using a HD for storage to extend ram is much too slow for many...
7
3964
by: Immortal Nephi | last post by:
My project grows large when I put too many member functions into one class. The header file and source code file will have approximately 50,000 lines when one class contains thousand member functions. Is it normal how C++ Compiler can compile large class without any problem? Didn't C++ Compiler have rules to limit the number of member functions? One big object has complex operations how member variables and member functions can be...
0
8685
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
8613
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
9032
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...
1
8908
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7745
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
5869
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
4626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2344
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
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.