How to determine whether a string is a number in java

Preface

Numbers are often represented and passed by strings in certain fields.So how do we tell if a string is a number?Let's talk about this topic today.

Empty characters and null

First, it's clear that empty characters''and null are definitely not numbers.We actually write the same logic.Some of the most extreme and easily discernible logical judgments are directly preferred.This is a small trick.

toCharArray

Strings that exclude previous situations can be converted to char arrays by the toCharArray() method.Character.isDigit(int) can easily tell if the char element is a number (don't ask why a char is an int!).Will this work?Let's work on a wave of situations:

public class Main {
    public static void main(String[] args) {
        // false
        System.out.println("\"\"  Is it a number: "+isNumeric(""));
        // false
        System.out.println("\" \"  Is it a number: "+isNumeric(" "));
        // false
        System.out.println("null  Is it a number: "+isNumeric(null));
        // false
        System.out.println("1,200  Is it a number: "+isNumeric("1,200"));
        // true
        System.out.println("1  Is it a number: "+isNumeric("1"));
        // Expected negative but false
        System.out.println("-1  Is it a number: "+isNumeric("-1"));
        // true
        System.out.println("200  Is it a number: "+isNumeric("200"));
        // Expect two floating point numbers to remain false
        System.out.println("3000.00  Is it a number: "+isNumeric("3000.00"));
        // Binary
        System.out.println("0b11001  Is it a number: "+isNumeric("0b11001"));
        // Octal true
        System.out.println("012  Is it a number: "+isNumeric("012"));
        // Hexadecimal false
        System.out.println("0x12  Is it a number: "+isNumeric("0x12"));
        //  A-F stands for 10-15 false in hexadecimal
        System.out.println("0xAF  Is it a number: "+isNumeric("0xAF"));
        // double false
        System.out.println("12.12d  Is it a number: "+isNumeric("12.12d"));
        // double scientific counting false
        System.out.println("12E4  Is it a number: "+isNumeric("12E4"));
        // float  false
        System.out.println("12.123f  Is it a number: "+isNumeric("12.123f"));
        // Separator jdk1.7 false
        System.out.println("1_000_000  Is it a number: "+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 you can see from the above, there are not too many problems with positive decimal integers of moderate moments.Once it is one of floating point numbers, decimal numbers, negative numbers, binary, hexadecimal, scientific counting, and separators, this method is not very useful.Suddenly it occurred to me that there were some ways to use packaging classes.

parse

The wrapper classes of numbers have corresponding parse methods.A NumberFormatException exception is thrown if the string does not conform to the rules for the corresponding number type.So let's change our judgment here:

   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;
                }
            }
        }
    }

After another execution, the following results are obtained:

Is''a number: false
 Is''a number: false
 Is null a number: false
 Is 1,200 a number: false
 Is 1 a number:true
 -1 Is it a number:true
 200 is not a number:true
 Is 3000.00 a number:true
 0b11001 is not a number: false
 012 is not a number:true
 0x12 is not a number: false
 0xAF is not a number: false
 Is 12.12d a number:true
 Is 12E4 a number:true
 Is 12.123f a number:true
 Is 1_000_000 a number: false

From the fifth line above, the representation of numbers is supported in java.From the execution results, all but binary, hexadecimal, and separator characters are expected.Although this approach is not perfect, we can also learn some rules about the parse method.That's the point.

Third Party Class Library

That is, the api provided by jdk does not have a silver bullet.So is there a third-party library to detect?We used the NumberUtils tool class provided in the commons-lang3 library (version 3.9) to do this. I tested the isParsable, isDigits, and isCreatable methods separately and found that the isCreatable method works best, with only the delimiters not meeting our expectations.If you don't consider this, isCreatable should be basically what you need.Other libraries don't know which one you know will work best through my public number: Felordcn told me.Also welcome to my personal blog: https://felord.cn

summary

Today, through some validation of whether strings are java's number types, let's review how numbers in Java are represented and converted.A few rules were found.I'm sure this article will impress you more with the numbers in Java and help you with your work.

Focus on Public Number: Nung Nong Little Fat for more information

Keywords: Programming Java JDK

Added by sageman on Fri, 27 Sep 2019 07:56:52 +0300