isInteger, isFloat functions?

D

D. Alvarado

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
 
R

RobG

D. Alvarado said:
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.
 
F

Fox

RobG said:
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("123abc") 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.
 
F

Fox

D. Alvarado said:
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]
 
E

Evertjan.

D. Alvarado wrote on 20 sep 2004 in comp.lang.javascript:
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!
 
P

Philip Ronan

D. Alvarado wrote on 20 sep 2004 in comp.lang.javascript:

t = " -12.345"
alert(!/\./.test(t) && +t==t)
t = " -12345"
alert(!/\./.test(t) && +t==t)


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

Shoot!

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

Evertjan.

Philip Ronan wrote on 20 sep 2004 in comp.lang.javascript:
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 ?
 
P

Philip Ronan

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)
 
F

Fred Oz

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
 
E

Evertjan.

Philip Ronan wrote on 20 sep 2004 in comp.lang.javascript:
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 ?
 
F

Fred Oz

Philip Ronan wrote:

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

1/0 is not infinity, is it "undefined"- as is the result
of any division by zero.

Cheers, Fred.
 
P

Philip Ronan

Philip Ronan wrote:



1/0 is not infinity, is it "undefined"- as is the result
of any division by zero.

Cheers, Fred.

Really?
javascript:alert(1/0) returns "Inf" in IE.
 
E

Evertjan.

Andrew Thompson wrote on 20 sep 2004 in comp.lang.javascript:
All three of IE 6.0026, Moz. 1.7 and Opera 6.54
give consistent results for me..

javascript:alert(1/0) -> 'Infinity'
javascript:alert(0/0) -> 'NaN'
javascript:alert(-1/0) -> '-Infinity'

Makes perfect sense to me.

And which of them are integers ?
;-}
 
M

Michael Winter

[snip]
Testing strings using regular expressions to see if they have
decimal places (and how many), surplus characters, scientific
notation, etc. requires exhaustive testing [...]

Not at all:

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

ensures that the string contains an integer with no leading zeros.

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

allows for signed integers.

To check for basic real numbers, it can be modified to:

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

which allows integer or real number inputs. To force decimal places and to
limit their number again, only simple modification is necessary:

/^(0|[1-9])\d*\.\d+$/ // must be real
/^(0|[1-9])\d*\.\d\d$/ // must be real with two decimal places
/^(0|[1-9])\d*\.\d{1,5}$/ // must be real with at most five d.p.

Scientific notation:

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

Optional scientific notation:

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

Optional scientific notation with positive and negative numbers:

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

Mandatory canonical scientific notation:

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

Hexadecimal:

/^0x[0-9a-f]+$/i

[Note: these are untested]

The problem with using parseInt and parseFloat is that parsing stops at an
unrecognised character. That doesn't really tell you if the value's format
is correct or not, just that part of it converts to a number. If you want
check an input format, regular expressions are the best approach.

As you can see from the above, it doesn't take much effort once you've
established some basic patterns. After that point, it's simply a matter of
adding the components in the appropriate places.
How about:

var x = someValue;
if (x == parseInt(x) && x == parseFloat(x)) {

Calling parseInt without a radix argument can be unpredictable. Don't do
it.

[snip]

Mike
 
D

Dr John Stockton

JRS: In article <[email protected]>,
dated Sun, 19 Sep 2004 19:10:21, seen in D.
Alvarado said:
Does anyone have handy functions for testing whether a text field value is

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

At least for the first case, the test might or might not need to
include/exclude a sign and/or zero itself.

Floating-point numbers are of the form +12.345E-6 ; you may instead
want to accept only fixed-point <digits> optional: <point><digits> .

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

Normally, one can limit the number of digits in an integer of fixed-
point number.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Mon, 20 Sep
2004 01:05:33, seen in Fox
D. Alvarado wrote:
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);

return /^\d+$/.test(n) // seems simpler
return /^[+-]?\d+$/.test(n) // seems better
}
b) a valid floating point number?

function
isFloat(s)
{
var n = trim(s);
return n.length>0 && !(/[^0-9.]/).test(n) && (/\.\d/).test(n);

return /^[+-]?\d+(\.\d+)?$/.test(n) // seems better
// but the function deals with fixed-, not floating-, point.
}


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.

That should be done, if circumstances permit; international
recommendations deprecate a decimal point that it not surrounded by
digits.
 
L

Lee

Philip Ronan said:
Really?
javascript:alert(1/0) returns "Inf" in IE.

Really.
Division by zero is no more a mathematical operation than is cracking an egg.
Any numeric value assigned to it is simply a convenient fiction.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Mon, 20
Sep 2004 10:15:21, seen in Evertjan.
t = "1.2e+33"
alert(!/\./.test(+t) && +t==t)

Though technically incorrect [John?],
are such big/small numbers important to the OP ?

I think all such tests ate liable to fail with long numbers.
Long != big.
Also 125.1 fails, 125.0 passes.
IMHO, the method is basically unpredictable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,061
Latest member
KetonaraKeto

Latest Threads

Top