Best way to check if a Java String is a number.
One of the routine tasks in many Java applications is to convert a string to a number. For instance, you may have a form where user submits his or her age. The input will come to your Java application as a String but if you need the age to do some calculation you need to convert that String into a number.
Like,
int age = new Integer(ageString).intValue();
But there is a possibility that the user might have entered an invalid number. Probably they entered “thirty” as their age.
If you try to convert “thirty” to a number you will get NumberFormatException. One way to avoid this is to catch and handle the NumberFormatException. But this is not the ideal and the most elegant solution to convert a string to a number in Java.
Another approach is to validate the input string before performing the conversion using Java regular expression. I like that second approach because it is more elegant and it will keep your code clean.
Here is how you can validate if a String value is numeric using Java regular expression.
import java.util.regex.Matcher; import java.util.regex.Pattern; /*A Java class to verify if a String variable is a number*/ public class IsStringANumber{ public static boolean isNumeric(String number){ boolean isValid = false; /*Explaination: [-+]?: Can have an optional - or + sign at the beginning. [0-9]*: Can have any numbers of digits between 0 and 9 \\.? : the digits may have an optional decimal point. [0-9]+$: The string must have a digit at the end. If you want to consider x. as a valid number change the expression as follows. (but I treat this as an invalid number.). String expression = "[-+]?[0-9]*\\.?[0-9\\.]+$"; */ String expression = "[-+]?[0-9]*\\.?[0-9]+$"; CharSequence inputStr = number; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()){ isValid = true; } return isValid; } }
The code above is self-explanatory. I explained the logic on how to build the regular expression to validate that a string has all numeric digits. I then use Matcher and Pattern classes to test the input string against the regular expression. If the input string passes the regular expression validation the method will return true, indicating that the string contains a numeric value. If the input string does not match the regular expression the method will return false.
Enjoy.!
November 3, 2011 @ 1:32 pm
It does not work for exponential numbers (e.g.: 0.1e-10).
Maybe using this regex is enough: “[-+]?[0-9]*\.?[0-9]+e[-]?[0-9]+$” (I’ve basically added ‘e[-]?[0-9]+’ at the end of your regex)
November 3, 2011 @ 1:52 pm
Sorry, the right regex is: ^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$
February 22, 2014 @ 5:11 am
Hello there, You have done a fantastic job. I will certainly digg it and personally suggest
to my friends. I am confident they’ll be benefited from this web site.
my web site; horror movies 2013
February 24, 2014 @ 3:57 am
At times, the by a bowel deals too much or even as well powerfully,
and so foodstuff techniques from the digestive system too quickly, causing diarrhea.
Other instances, the particular intestinal muscle tissue deal nevertheless
don’t unwind all over again, or even these people commitment very slowly but surely, leading to constipation.
These kind of crazy, out-of-sync lean muscle motions usually are
powering this agony of IBS, comparable to lean muscle jerks in your lower-leg bring about the ache of the
charley horse. All of us get intestinal tract gasoline, but for people with IBS, it could come to be stuck interior,
causing bloating as well as distention.
Also visit my web blog IBS Cure
March 3, 2014 @ 3:53 pm
Greetings! Very helpful advice within this post! It is the little changes which
will make the most important changes. Thanks a lot for sharing!
March 9, 2014 @ 5:33 am
We stumbld over here by a different page and thought I may as well check
thigs out. I like wat I see so now i’m following you. Look forward to exploring your web page again.
March 13, 2014 @ 11:42 am
I go to see every day a few web pages and websites to read content, except this website
presents quality based content.
March 14, 2014 @ 3:42 am
I loved as much as you will receive carried out right here.
The sketch is tasteful, your authored subject
matter stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following.
unwell unquestionably come further formerly again since exactly
the same nearly a lot often inside case you shield this increase.
March 15, 2014 @ 5:17 am
This design is wicked! You certainly know how to keep a reader entertained.
Between your wit and your videos, I was almost moved
to start my own blog (well, almost…HaHa!) Wonderful job.
I really enjoyed what you had to say, and more than that,
how you presented it. Too cool!
March 15, 2014 @ 1:06 pm
Thanks for another fantastic article. Where else may anyone get that kind of information
in such an ideal means of writing? I have a presentation subsequent week, and I’m at
the look for such information.
March 17, 2014 @ 7:43 am
I’ll right away grasp your rss as I can not find your e-mail subscription link or e-newsletter service.
Do you have any? Please permit me know so that I may subscribe.
Thanks.
March 21, 2014 @ 1:02 pm
If you’re searching for tips related to penny stocks, there are several obtainable.
The most striking reason is that the recession period is
going on throughout the world and the investors can invest with
a small amount of money. Are you looking to trade penny stocks to earn
a good return on your investment.
March 21, 2014 @ 10:16 pm
Hi, i feel that i saw you visdited my web site thus i came to go back the prefer?.I’m attempting to in finding issues to improve mmy web site!I assume its good
enough to use some of your ideas!!
March 27, 2014 @ 11:45 am
A personal blog is a smart statement, so why not start blogging now.
Whenever I write an article, I see to it that I will have a good transition leading my readers to my website.
Then to share the good news of what you can do to control it and not let it ruin your life.
It is common for people to blog instead of set up an online site because they lack the funds.
– And the simplest way to make profit from blogging is by
allowing Google Adsense or any other ads on your blog.
my web page :: nitin yadav personal blog
April 2, 2014 @ 1:58 pm
This design is incredible! You most certainly know how
to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!)
Great job. I really loved what you had to say,
and more than that, how you presented it.
Too cool!
My blog post; casette da giardino
April 4, 2014 @ 1:49 pm
I read this piece of writing completely about the resemblance of most recent and earlier
technologies, it’s remarkable article.
April 7, 2014 @ 4:01 pm
Hi there, I found your website by way of Google even
as searching for a comparable subject, your site got here up, it appears good.
I’ve bookmarked it in my google bookmarks.
Hello there, simply became aware of your blog through Google, and found that it’s really informative.
I am gonna watch out for brussels. I’ll appreciate in the
event you proceed this in future. Lots of other folks might be benefited out of your writing.
Cheers!
April 10, 2014 @ 5:30 am
Hey I know this is off topic but I was wondering if you knew of any widgets I could
add to my blog that automatically tweet my newest
twitter updates. I’ve been looking for a plug-in like this for
quite some time and was hoping maybe you would have some experience with something like this.
Please let me know if you run into anything.
I truly enjoy reading your blog and I look forward to your new updates.
Also visit my website :: endometriosis
April 10, 2014 @ 9:18 am
Having read this I thought it was very informative.
I appreciate you taking the time and energy to put this article together.
I once again find myself spending way too much
time both reading and commenting. But so what,
it was still worth it!
Have a look at my page radang payudara
April 19, 2014 @ 11:52 am
Hey There. I discovered your blog using msn. This is an extremely neatly written article.
I’ll make sure to bookmark it and come back to learn extra of your useful information.
Thank you for the post. I will certainly return.
Here is my homepage :: obat penghilang bau ketiak
April 19, 2014 @ 3:23 pm
Hi there, after reading this awesome paragraph i am as well happy to share my
knowledge here with colleagues.
Here is my web site – kulup panjang
April 19, 2014 @ 11:34 pm
I like what you guys are usually up too. This kind
of clever work and coverage! Keep up the wonderful works
guys I’ve added you guys to our blogroll.
Also visit my web site; radang panggul
April 20, 2014 @ 12:26 am
magnificent post, very informative. I ponder why the other specialists of
this sector don’t understand this. You must continue your
writing. I’m sure, you have a great readers’ base already!
My webpage: endometriosis
April 23, 2014 @ 11:12 pm
This article presents clear idea for the new people of blogging, that truly how to do blogging and site-building
April 24, 2014 @ 7:45 am
Just desire to say your article is as amazing.
The clearness in your post is simply excellent and i can assume you’re an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please continue the rewarding work.
April 26, 2014 @ 9:18 am
What’s up to every body, it’s my first go to see of this blog; this
website consists of amazing and truly excellent stuff in support of visitors.
Also visit my homepage … Impotensi
April 27, 2014 @ 6:06 pm
Hey There. I discovered your weblog the usage of msn.
That is a really smartly written article. I will
make sure to bookmark it and come back to learn extra of your helpful information.
Thank you for the post. I’ll certainly return.
my weblog – bau ketiak
May 6, 2014 @ 12:01 pm
An outstanding share! I have just forwarded this onto a coworker
who had been conducting a little research on this.
And he in fact bought me dinner simply because I stumbled upon it for him…
lol. So let me reword this…. Thanks for the meal!!
But yeah, thanks for spending time to discuss this matter here
on your internet site.
May 22, 2014 @ 5:59 am
I all the time emailed this webpage post page to all my contacts, as if like
to read it next my contacts willl too.
May 22, 2014 @ 10:09 pm
I am now not certain the place you’re getting your info,
however good topic. I needs to spend some time studying more or understanding
more. Thanks for fantastic information I was looking
for this information for my mission.
September 7, 2014 @ 1:56 pm
This is my first time pay a visit at here and i am really happy to read everthing at single
place.
October 2, 2014 @ 3:13 am
you’re truly a good webmaster. The web site loading
velocity is incredible. It sort of feels that you’re doing any distinctive trick.
Furthermore, The contents are masterpiece. you have performed a wonderful job on this subject!
October 12, 2014 @ 9:44 am
This is my very first time to visit here. I found so many entertaining stuff in your weblog,
especially in its discussion. I guess I’m not the
only one having all the entertainment here!
Keep up the outstanding work.
October 14, 2014 @ 8:27 pm
I am regular reader, how are you everybody?
This paragraph posted at this site is really nice.
November 30, 2014 @ 12:01 pm
“Space Travel and the Effects of Weightlessness on the Human Body”
Candian Space Agency:. Here is an outline of the different types of jobs available for travel photographers
and what kind of equipment they will need to have.
Everyone admires the idea of travelling though the motives, passions and preferences
of travelling are completely different.
December 10, 2014 @ 4:00 pm
” is perfectly grammatically correct but is passive in its voice. This open architecture, in and of itself, leads to much of the confusion about voice. The DSP Inverter Technology is the true digital signal processor with added 20 percent power conversion rate compare to transistor generators.
July 24, 2015 @ 4:10 am
I’m not sure exactly why butt this website iss oading incrwdibly slow
for me. Is anyone else having this problem or iis it
a issue on my end? I’ll checck back later on aand see if the problem srill exists.
September 3, 2015 @ 8:45 pm
Wow tha was odd. I just wroe an extremely long comment but after
I clicked submit my comment didn’t appear. Grrrr… well I’m nnot
writiong all that oer again. Anyways, just wanhted
to say great blog!
February 18, 2016 @ 10:07 pm
Hello, this weekend is good in support of me, because this occasion i am
reading this great informative paragraph here at my home.