How to determine whether a string is a number in java

Foreword

Numbers in some areas often used to represent strings and transfer. So how do we determine whether a string is the figure? Today we explore this topic.

Null null character and

First, we can clearly know that the null character ""and null certainly not a number. In fact, we write the same as other logic. Some of the most extreme easiest discrimination processing logic determines the priority for processing directly. This is a little trick.

toCharArray

Negative previous case string can toCharArray() be converted to char array method. And Character.isDigit(int) it is easy to determine whether the char element is digital (do not ask why char int!). Then the method will not work? We wave to operate a variety of situations:

public class Main {
    public static void main(String[] args) {
        // false
        System.out.println("\"\"  是不是数字: "+isNumeric(""));
        // false
        System.out.println("\" \"  是不是数字: "+isNumeric(" "));
        // false
        System.out.println("null  是不是数字: "+isNumeric(null));
        // false
        System.out.println("1,200  是不是数字: "+isNumeric("1,200"));
        // true
        System.out.println("1  是不是数字: "+isNumeric("1"));
        // 预期是负数  却为 false
        System.out.println("-1  是不是数字: "+isNumeric("-1"));
        // true
        System.out.println("200  是不是数字: "+isNumeric("200"));
        // 预期是保留两位的浮点数  却为false
        System.out.println("3000.00  是不是数字: "+isNumeric("3000.00"));
        // 二进制
        System.out.println("0b11001  是不是数字: "+isNumeric("0b11001"));
        // 八进制  true
        System.out.println("012  是不是数字: "+isNumeric("012"));
        // 十六进制 false
        System.out.println("0x12  是不是数字: "+isNumeric("0x12"));
        //  A-F 代表十六进制中的 10-15   false
        System.out.println("0xAF  是不是数字: "+isNumeric("0xAF"));
        // double false
        System.out.println("12.12d  是不是数字: "+isNumeric("12.12d"));
        // double 科学计数法   false
        System.out.println("12E4  是不是数字: "+isNumeric("12E4"));
        // float  false
        System.out.println("12.123f  是不是数字: "+isNumeric("12.123f"));
        // 分隔符   jdk1.7      false
        System.out.println("1_000_000  是不是数字: "+isNumeric("1_000_000"));

    }

    public static boolean isNumeric(final String str) {
        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        }
        return str.chars().allMatch(Character::isDigit);
    }
}
复制代码

As can be seen from the above, law-abiding, positive decimal integer without too many problems. Once a floating point decimal, negative, binary, hexadecimal, scientific notation, the separator case where one, this method is not handy. Suddenly thought of packaging and some methods are available.

parse

Digital wrapper class has a corresponding parsemethod. If the string does not comply with the corresponding figure types of rules will throw NumberFormatException an exception. So here we change our judgments about the method:

   public static boolean isNumeric(final String str) {
        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        }

        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            try {
                Double.parseDouble(str);
                return true;
            } catch (NumberFormatException ex) {
                try {
                    Float.parseFloat(str);
                    return true;
                } catch (NumberFormatException exx) {
                    return false;
                }
            }
        }
    }
复制代码

Then execute it, the following results:

""  是不是数字: false
" "  是不是数字: false
null  是不是数字: false
1,200  是不是数字: false
1  是不是数字: true
-1  是不是数字: true
200  是不是数字: true
3000.00  是不是数字: true
0b11001  是不是数字: false
012  是不是数字: true
0x12  是不是数字: false
0xAF  是不是数字: false
12.12d  是不是数字: true
12E4  是不是数字: true
12.123f  是不是数字: true
1_000_000  是不是数字: false
复制代码

Starting from the fifth row of the above, the digital representation of all java supported. From the results point of view in addition to binary, hexadecimal, other delimiters it is in line with expectations. Although this method is not perfect, but we also learn from some of the rules corresponding to the parse method. That is the key.

Third-party libraries

That api jdk provided and no silver bullet. So if there are third-party libraries to detect it? We use the commons-lang3 library (version 3.9) provided NumberUtilstools for processing, its me isParsable, isDigits, isCreatable methods were tested isCreatable method works best, but 分隔符did not meet our expectations. If you do not consider this situation should be isCreatable to meet the basic needs. Other libraries do not know if you know what I'm easy to use by public number: Felordcn tell me. Also welcome to visit my personal blog station: felord.cn

Regular Expressions

In fact, the use of regular expressions is the perfect solution to the problem.

to sum up

Today, by some validation java string is numeric types, allowing us to java in the digital conversion and how to represent and reviewed. We found some from a lot of rules. I believe this article will let you have a more profound impression on java in numbers, but also want to help your work.

Original author: fat brother small farming code reproduced address: gper.club/articles/7e...

Guess you like

Origin juejin.im/post/5db6841ee51d452a06698b92