Skip to content

Instantly share code, notes, and snippets.

@Ilya-Gazman
Last active November 5, 2017 17:45
Show Gist options
  • Save Ilya-Gazman/ad180409c11244fa2401b3a8f8f8b712 to your computer and use it in GitHub Desktop.
Save Ilya-Gazman/ad180409c11244fa2401b3a8f8f8b712 to your computer and use it in GitHub Desktop.
Determine if a String is an Integer in Java
/**
* Created by Ilya Gazman on 6/29/2017.
*/
public class NumberTester {
public static final String MIN_VALUE_32 = Integer.MIN_VALUE + "";
public static final String MAX_VALUE_32 = Integer.MAX_VALUE + "";
public static final String MIN_VALUE_64 = Long.MIN_VALUE + "";
public static final String MAX_VALUE_64 = Long.MAX_VALUE + "";
public static boolean isInteger64(String value) {
return isInteger(value, MIN_VALUE_64, MAX_VALUE_64);
}
public static boolean isInteger32(String value) {
return isInteger(value, MIN_VALUE_32, MAX_VALUE_32);
}
private static boolean isInteger(String value, String minValue, String maxValue) {
if (value == null) {
return false;
}
int length = value.length();
if (length == 0) {
return false;
}
int i = 0;
if (value.charAt(0) == '-') {
if (length == 1) {
return false;
}
if (length > minValue.length()) {
return false;
}
i = 1;
maxValue = minValue;
} else if (length > maxValue.length()) {
return false;
}
for (; i < length; i++) {
char c = value.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
if (length < maxValue.length()) {
return true;
}
if (length > maxValue.length()) {
return false;
}
for (i = 0; i < length; i++) {
if (value.charAt(i) > maxValue.charAt(i)) {
return false;
}
if (value.charAt(i) < maxValue.charAt(i)) {
return true;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment