How to check if a string is 'float' or 'int'
Asked Answered
P

4

6

I have a string, and I know that it only contains a number.

How can I check if this number is int or float?

Perilous answered 1/4, 2017 at 11:9 Comment(0)
D
23

There are many ways to solve your problem. For example, you can use try{}catch(){}:

Solution 1

public static void main(String[] args) {
    String str = "5588";

    // Check if int
    try {
        Integer.parseInt(str);
    } catch(NumberFormatException e) {
        // Not int
    }

    // Check if float
    try {
        Float.parseFloat(str);
    } catch(NumberFormatException e) {
        // Not float
    }
}

Solution 2

Or you can use regex [-+]?[0-9]*\.?[0-9]+:

boolean correct = str.matches("[-+]?[0-9]*\\.?[0-9]+");

For more details, take a look at Matching Floating Point Numbers with a Regular Expression.

Dari answered 1/4, 2017 at 11:16 Comment(5)
The regex suggested as a solution is not valid. It does not accept negative sign, and it accepts weird strings like 3. or even just .Evocation
@Evocation this is correct and this was from a long time when I start learning regex I fix my mistake hope this can help moreDari
Yes the new one looks good. \\d can still work instead of [0-9] but maybe in this case the intent is clearer (since it is parsing a number).Evocation
both Integer.parseInt("1") and Float.parseFloat("1") will not throw exceptionVinasse
@Vinasse Correct. That's why you do the tests in this order. You should stop when you get a success, instead of trying both. I'm not in favour of a regex solution. Use the facilities provided for the purpose.Hedonic
V
0

In the 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"));
Viewy answered 22/8, 2020 at 3:10 Comment(1)
But this will not inform whether the String is Int or Float right? It will return true irrespective of it, right? This will inform only if its some sort of number. We need a another check to confirm if its Int or Float.Laforge
D
0

I want to expand on what Youcef LAIDANI and Peter Mortensen had posted in regards to the regex.

Solution 2

Or you can use regex [-+]?[0-9]*\.?[0-9]+:

boolean correct = str.matches("[-+]?[0-9]*\\.?[0-9]+");

Instead, we need to expand what the regex means. This will allow us to write it to fit your needs.

str.matches("[-+]?[0-9]*\.?[0-9]+"): This is a call to the matches() method of the String class. It checks if the string str matches the specified regular expression pattern.

  • [-+]? : This part of the regex matches an optional positive or
    negative sign. The [-+] means either a hyphen or a plus sign, and the ? makes it optional.

  • [0-9]* : This matches any sequence of digits (0-9), including zero occurrences (hence the * quantifier).

  • \\.? : This matches an optional decimal point. The backslash ( \ ) is an escape character, and . matches any character, so \. specifically matches a period. Then the ? makes it optional.

  • [0-9]+ : This matches one or more digits (0-9).

The real problem with the regex posted is that it would be correct for both an integer and a float.

So what would actually be needed then is to be able to check if there is a period or not, and that is about it. This can be done with regex, but lets put it in a manner that would more suit the question. The key here is looking at my example and notice where I have ( \\. ) in the regex, this means a period is required. Also notice that I always require a number after the period by placing a + after the [0-9]. If there is no number after the period, that should be considered a string.

Option 1 If you always have a positive number but not necessarily a digit before the period

boolean isFloat = str.matches("[0-9]*\\.[0-9]+");
boolean isInt = str.matches("[0-9]+");

Option 2 If you want the +- option in the beginning

boolean isFloat = str.matches("[+-]?[0-9]*\\.[0-9]+");
boolean isInt = str.matches("[+-}?[0-9]+");

Option 3 If you want to ensure there is a number before the period

boolean isFloat = str.matches("[+-]?[0-9]+\\.[0-9]+");
boolean isInt = str.matches("[+-]?[0-9]+");

If you just want something that returns "integer" or "float" you can use the str.matches with if statements instead.

if(string.matches("[+-]?[0-9]+")) {
    return "integer";
}
else if(string.matches("[+-]?[0-9]*\\.[0-9]*")) {
    return "float";
}
else {
    return "string";
}
Disqualification answered 14/5 at 0:28 Comment(0)
C
-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";
}
Chacha answered 3/3, 2022 at 19:49 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Praenomen
Mere code is not an answer. You have to explain. This code is far more complex than necessary.Hedonic

© 2022 - 2024 — McMap. All rights reserved.