Whether the Java decision string can be converted to a number

Source: Internet
Author: User

In Java operations, it often involves converting string strings to int numbers.

which strings can be converted to numbers, which cannot, and cannot always be judged by whether Integer.parseint () throws an exception.

Just met the conversion situation, summed up the next, share it out.


Defining Method signatures

[Java] view plain copy/** * To see if a string can be converted to a number * @param str string * @return true; False can/* public static Boolean isstr2num (String str) {}
How do you implement the method body? Two different ways


Method 1 Integer.parseint Conversion

[Java] view plain copy try {integer.parseint (str);   return true;   catch (NumberFormatException e) {return false; }

Method 2 Regular Expression

[Java] view plain copy pattern = pattern.compile ("^[0-9]*$");   Matcher Matcher = Pattern.matcher (str); return matcher.matches ();


Integer also has a static method valueof (String s) to view the source

[Java] view plain copy public static Integer valueof (String s) throws NumberFormatException {return inte   Ger.valueof (parseint (S, 10)); }

valueof (string s) also first converts the string to a number by parseint () before converting it to an integer object.

and parseint (String s) returns an int variable, saving the overhead of heap memory

[Java] view plain copy public static int parseint (String s) throws NumberFormatException {return Parsein   T (s,10); }
So, here's the judgment to use parseint on it. --This article is from: Whether the Java Judge string can be converted to a number

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.