I have a string of signed integer value that could range from "+2147483650" to "-9638527412". I need to parse them to a 32-bit integer, such that, when the string value is above the integer capacity (2^31) it should return the nearest possible integer value. Using "Integer.parseInt" is giving out of bound exception.
Example:
input: "+2147483650"
output: "+2147483647"
input: ""-963852741258"
output: "-2147483648"
I tried to use existing functions, but I'm stuck here.
try{
//num =Integer.valueOf(stringNumber);
num =Integer.parseInt(stringNumber);
}catch(Exception e){
num = -2147483648; // if stringNumber is negative
num = +2147483647 // if stringNumber is positive
}
# Answer 1
Since your value range is limited to "+2147483650" to "-9638527412", you can parse to long and check for overflow.
public static int parse(String stringNumber) {
long value = Long.parseLong(stringNumber);
return (value < Integer.MIN_VALUE ? Integer.MIN_VALUE :
value > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) value);
}
Test
System.out.println(parse("+2147483650"));
System.out.println(parse("42"));
System.out.println(parse("-9638527412"));
Output
2147483647
42
-2147483648
# Answer 2
If there is no reason you can't use a larger datatype such as Long then you can just parse it as a Long. If the parse fails, it will throw a NumberFormatException.
try {
long tmp = Long.parseLong(stringNumber);
int result;
if (tmp < Integer.MIN_VALUE) {
result = Integer.MIN_VALUE;
} else if (tmp > Integer.MAX_VALUE) {
result = Integer.MAX_VALUE;
} else {
// safe cast to int (java 8)
result = Math.toIntExact(tmp);
}
// TODO do something with the result
} catch (NumberFormatException e) {
// could not parse
}
# Answer 3
Given the specified potential input range, this function will clamp the given string in the range [Integer.MIN_VALUE, Integer.MAX_VALUE]:
static int clampedStringValue(String s) {
long n = Long.parseLong(s);
if (n > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (n < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
} else {
return (int)n;
}
}