How to check if a String is numeric in Java

前端 未结 30 2574
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  悲哀的现实
    2020-11-21 05:56

    Based off of other answers I wrote my own and it doesn't use patterns or parsing with exception checking.

    It checks for a maximum of one minus sign and checks for a maximum of one decimal point.

    Here are some examples and their results:

    "1", "-1", "-1.5" and "-1.556" return true

    "1..5", "1A.5", "1.5D", "-" and "--1" return false

    Note: If needed you can modify this to accept a Locale parameter and pass that into the DecimalFormatSymbols.getInstance() calls to use a specific Locale instead of the current one.

     public static boolean isNumeric(final String input) {
        //Check for null or blank string
        if(input == null || input.isBlank()) return false;
    
        //Retrieve the minus sign and decimal separator characters from the current Locale
        final var localeMinusSign = DecimalFormatSymbols.getInstance().getMinusSign();
        final var localeDecimalSeparator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
    
        //Check if first character is a minus sign
        final var isNegative = input.charAt(0) == localeMinusSign;
        //Check if string is not just a minus sign
        if (isNegative && input.length() == 1) return false;
    
        var isDecimalSeparatorFound = false;
    
        //If the string has a minus sign ignore the first character
        final var startCharIndex = isNegative ? 1 : 0;
    
        //Check if each character is a number or a decimal separator
        //and make sure string only has a maximum of one decimal separator
        for (var i = startCharIndex; i < input.length(); i++) {
            if(!Character.isDigit(input.charAt(i))) {
                if(input.charAt(i) == localeDecimalSeparator && !isDecimalSeparatorFound) {
                    isDecimalSeparatorFound = true;
                } else return false;
            }
        }
        return true;
    }
    

提交回复
热议问题