The NumberFormat class will only parse the string until it reaches a non-parseable character:
((Number)NumberFormat.getInstance().parse("123e")).intValue()
will hence return 123.
Perhaps get the size of the string and loop through each character and call isDigit() on each character. If it is a digit, then add it to a string that only collects the numbers before calling Integer.parseInt().
Something like:
String something = "423e";
int length = something.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = something.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("result is: " + result);
Just go through the string, building up an int as usual, but ignore non-number characters:
int res = 0;
for (int i=0; i < str.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') continue;
res = res * 10 + (c - '0');
}
Replace all non-digit with blank: the remaining string contains only digits.
Integer.parseInt(s.replaceAll("[\\D]", ""))
This will also remove non-digits inbetween digits, so "x1x1x"
becomes 11
.
If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:
s.matches("[\\d]+[A-Za-z]?")
You can also use Scanner :
Scanner s = new Scanner(MyString);
s.nextInt();
Source: Stackoverflow.com