Groovy Tip 37 conversion between strings and numbers

Source: Internet
Author: User

The conversion between strings and numbers is a problem that we are bound to encounter in our project because the value of the variable we get from the user interface is definitely a string.

So, what we often have to do in the project is: first, you need to check the user's input to determine whether the user's input is a number; second, if so, we need to further convert it to numbers to facilitate our calculations.

In the Java language, we want to determine whether a string is a number, there are basically two methods, the first is directly to the conversion, if there are exception thrown, then the string is not the number we need. Here is a section of code that determines whether a string is an integer number:

public static boolean isInt(String str)
    {
       try
       {
           Integer.parseInt(str);
           return true;
       }
       catch(Exception e)
       {
           return false;
       }
}

Similarly, I would like to judge whether a string is float, double, or Boolean, and can be judged using this method.

The second approach is to judge by regular expressions, where no examples are given.

All in all, both of these methods require us to give the code to judge.

In the groovy language, the system has APIs to help us do this directly, quite simply. For example, if we need to determine whether a string is an int, we just need to write the following code:

def num = '23'

      println num.isInteger()

The results of the operation are:

True

If this is the following code:

def num1 = '2.3'

      println num1.isInteger()

The result of the run is:

False

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.