Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String to Integers the safe way

I have a little method that amongst other things also converts a string into an integer. Since the string is a parameter of the method I want to make sure that that string is convertable. So I was just wondering what would be the safest and / or fastest way.


Version A: Just leave it as it is and take the risks (which I'm trying to avoid)

public static int stringToInt(String param) {
        return Integer.valueOf(param);
}

(in terms of speed, what kind of difference would it make to version B and C?)


Version B: Catch the exception

public static int stringToInt(String param) {
        try {
                return Integer.valueOf(param);
        } catch(NumberFormatException e) {
                return -1;
        }
}

Version C: Check each letter of the string to see, if it's a digit number or not

public static int stringToInt(String param) {
        for(char c : param.toCharArray()) {
                if(!Character.isDigit(c))
                        return -1;
        }
        return Integer.valueOf(param);
}

Note that the parameter has to be a positive number and the -1 is supposed to be the "error value" in my little program, in other words, all three versions of methods would work perfectally fine in my program.

I'm very open to any other suggestion you can give me, so feel free to create your own version, if you think yours is better.

Thank you very much for your support in advance.

like image 478
felix fritz Avatar asked Jun 04 '13 00:06

felix fritz


People also ask

Can you convert a string into a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.

Which function can be used to convert strings to integers?

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.


5 Answers

Guava offers a utility method for this which returns null in case your String can't be parsed.

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Ints.html#tryParse(java.lang.String)

Integer result = Ints.tryParse("1");  //returns 1
Integer result = Ints.tryParse("-1"); //returns -1
Integer result = Ints.tryParse("a");  //returns null
like image 75
user828878 Avatar answered Oct 05 '22 21:10

user828878


First, note that version C is not bulletproof: it would reject negative numbers, and would not catch numbers that are too large.

Version B is OK, yet it makes the caller change the coding style: rather than catching an error and processing it together with other errors, the caller would need to check for -1 all the time. This may be suboptimal in situations where you read multiple integers, but the error processing does not depend on which particular one has failed. In addition, new coders using your API may forget to check for -1, and use the error code inadvertently.

That's why I would stay with the first option: the code using version A would look instantly familiar to anyone who knows Java API, without the need to learn what happens inside your function.

like image 42
Sergey Kalinichenko Avatar answered Oct 05 '22 20:10

Sergey Kalinichenko


I believe a modified B to throw an exception rather than returning -1 will be the best choice. It is good to throw the exception up to the level, where it can be processed to send the proper response to the user. Returning a value like -1 will make your code error prone. Assume that a different programmer is consuming your method and he/she just have the signature of your method. So it is not clear from the signature what he/she should code to handle an exception or error scenario. But if you throw the exception and add it to your method declaration then it will enable the other programmer to consume your method properly alongwith the required exception handling. For me this looks the best:

public static int stringToInt(String param) throws NumberFormatException {
        try {
                return Integer.valueOf(param);
        } catch(NumberFormatException e) {
               // return -1;
               throw e;
        }
}
like image 21
Juned Ahsan Avatar answered Oct 05 '22 20:10

Juned Ahsan


Java 8 without any API:

 Optional.ofNullable(strNum)
         .map(Integer::valueOf).orElse(null);
like image 25
Clifford Fernandes Avatar answered Oct 05 '22 20:10

Clifford Fernandes


public int stringToInt(String param) throws NumberFormatException {

    Optional.ofNullable(param.replaceAll("\\s+", ""))
         .map(Integer::valueOf).orElse(null);

/*
                      or

    Optional.ofNullable(param.replaceAll(" ", ""))
         .map(Integer::valueOf).orElse(null);

*/

}

use the replaceAll to replace white spaces the plus is cpu friendly even though seems not needed.

like image 20
N Djel Okoye Avatar answered Oct 05 '22 19:10

N Djel Okoye