'How to check a string is float or int?

I have a string and I know that is only contained a number.

I want to check this number is int or float.



Solution 1:[1]

Late to the party . In Apache Commons NumberUtils class.

NumberUtils.isCreatable(String) which checks whether a String is a valid Java number or not.

    log.info("false {} ", NumberUtils.isCreatable("NA.A"));
    log.info("true {} ", NumberUtils.isCreatable("1223.589889890"));
    log.info("true {} ", NumberUtils.isCreatable("1223"));
    log.info("true {} ", NumberUtils.isCreatable("2.99e+8"));

Hope this helps someone.

Solution 2:[2]

public static String getPrimitiveDataTypeForNumberString(String str) {
    try {
        if (str.matches("^[\\p{Nd}]+[Ll]$")) {
            str = str.substring(0, str.length() - 1);
            long l = Long.parseLong(str);
            if (l <= Long.MAX_VALUE) {
                return "Long";
            }
        } else if (str.matches("^[\\p{Nd}]+[.][\\p{Nd}Ee]+[Ff]$")) {
            str = str.substring(0, str.length() - 1);
            float f = Float.parseFloat(str);
            if (f <= Float.MAX_VALUE) {
                return "Float";
            }
        } else if (str.matches("^[\\p{Nd}]+[.][\\p{Nd}Ee]+[Dd]$")) {
            str = str.substring(0, str.length() - 1);
            double d = Double.parseDouble(str);
            if (d <= Double.MAX_VALUE) {
                return "Double";
            }
        } else if (str.matches("^[\\p{Nd}]+$")) {
            double d = Double.parseDouble(str);
            if (d <= Integer.MAX_VALUE) {
                return "Integer";
            } else if (d <= Long.MAX_VALUE) {
                return "Long";
            } else if(d <= Float.MAX_VALUE) {
                return "Float";
            } else if(d <= Double.MAX_VALUE) {
                return "Double";
            }
        } else if (str.matches("^[\\p{Nd}]+[.][\\p{Nd}Ee]+$")) {
            double d = Double.parseDouble(str);
            if (d > Float.MAX_VALUE) {
                return "Double";
            }
            return "Float";
        }
    } catch (NumberFormatException e) {
    }

    return "Unknown";
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PremKumarR
Solution 2 Saquib Islam