473,836 Members | 1,417 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

test if a string is an integer?

I am reading input from a form. I want to validate the input by making sure
that the string is actually an integer. How would I do this? Do i need to
convert it to a character array and break down each character and test it?
or is there an easier way? Thanks.
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.720 / Virus Database: 476 - Release Date: 7/14/04
Jul 17 '05
10 199271
Tony Morris sez:
I am reading input from a form. I want to validate the input by making

sure
that the string is actually an integer. How would I do this? Do i need to
convert it to a character array and break down each character and test it?
or is there an easier way? Thanks.


This question has been asked many times.
You'll receive answers ranging from checking that each char is between '0'
and '9' through to the use of regular expressions.
All of these suggestions are severely flawed, offering no benefit, and in
most cases creating a hindrance (i.e. not neutral side-effects).

The reason that these suggestions are attempted is because nobody (assuming
everybody knows what they are doing) likes catching a RuntimeExceptio n, and
especially not for the purpose of control flow. There is no suitable
alternative.

If it really bothers you (as it does me), encapsulate the "brokenness " in a
single method:

public boolean isParsableToInt (String i)
{
try
{
Integer.parseIn t(i);
return true;
}
catch(NumberFor matException nfe)
{
return false;
}
}

Note that there is a slight performance penalty for doing this


FVO "slight" heavily dependent on quality of the input: for
input string that are mostly not valid Java ints the slowdown
can be an order of magnitude, compared to the same number of
input strings that are mostly valid Java ints. (Note that
"integer" != "Java int": a number outside of 32-bit int range
is still a perfectly good integer.)
(It gets better when you get to floating-point numbers: last
I checked Double.parseDou ble() didn't understand "1e-3" or
"+inf".)

To sum it up: there are two ways:

..parseXXX() actually converts string to number and comes
with exception overhead. You want to use it if you need to
convert the strings. You don't want to use when parsing huge
amounts of strings that are known to be mostly not Java
numbers.

Regexp and looking at the string character-by-character are
the same method, the only difference is performance of
regex match vs. that of your hand-rolled code. (And, of
course, quality of your code/regexp.) It does not convert
strings to numbers. It can recognize valid numbers that
are not "Java valid numbers".

Take your pick.

Dima
--
True courage comes from steadying yourself and forcing yourself to ssh into the
fscking thing yet again and not admitting that it doesn't care what it's done
to your life. -- "Hidden among the nodes" by ADB
Jul 17 '05 #11

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

Similar topics

3
1560
by: codefixer | last post by:
Hi, Does anybody know how to test string library functions ? I have already gone through "gcc-3.4.1/gcc/testsuite/gcc.c-torture/execute" I want to know if their is any other way to test the same. Thanks.
3
8697
by: Rob | last post by:
I have a 3 character string that I want to test to see if it is a positive integer... I could test that each individual character is >=0 and <=9... is there a better way ? Is there an IsInteger() function ?
6
7005
by: comp.lang.php | last post by:
I'm involved in a rather nasty debate involving a strange issue (whereby the exasperated tell me to RTFM even after my having done so), where this is insanely possible: print_r(is_int('1')); // PRINTS NOTHING print_r(strlen((int)1)); // PRINTS '1' Now I understand that in PHP, everything scalar is a string and can
4
2650
by: Chris | last post by:
Hi Everyone, I am using a regex to check for a string. When all the file contains is my test string the regex returns a match, but when I embed the test string in the middle of a text file a match is never returned. The string that I give to the regex is one that contains the entire contents of a text file. I'm using the multi-line option and I've also tried stripping out the VbCr
10
4940
by: David T. Ashley | last post by:
What is the most economical test in 'C' for "integer is a power of 2"? For example, something better than: void is_2_pow(int arg) { return((x == 1) || (x == 2) || (x == 4) || (x == 8) || (x == 16) /* and so on */ ); }
7
30220
by: laura | last post by:
Hi, I have a variable of type double. I need to know if there is an integer number store there. How can I test that ? I also have a default precision for doing this operation. Many thanks, Laura
5
3254
by: zivon | last post by:
Hello everyone ! I made a price calculator for a guest house. I have diffrent sale campaigns, all the time, I made a table with campaign name and discount, for example: name "pensioners" discount "*0.9". 10% discount, now I want calculate this with the price. The price is integer, and the discount must be a string, because of the */- how can I calculate them anyway ?
4
2794
by: smartic | last post by:
how to test string whether it contains special characters -------------------------------------------------------------------------------- please help dear experts on how to test string especially in username for example wheter it contains special charater and will return invalid ex for special characters (",',#,!,>,<,?) except any letters for other languages ?
0
9813
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
10831
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...
1
10582
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
10247
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
9367
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...
1
7778
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6976
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
4446
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
4005
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.