My goal is to take the digits out of a string and convert it to an int. For example: 12.7 (string) would become 127 (int) 156-06 (string) would become 15606 (int)
This is the code I used:
private static int convertToDigits(String input){
StringBuilder sb = new StringBuilder(input.length());
for(int i = 0; i < input.length(); i++){
char c = input.charAt(i);
if(c > 47 && c < 58){
sb.append(c);
}
}
String result = sb.toString().trim();
Log.d("Result", result);
return Integer.parseInt(result);
}
When I log the result I am getting 127 as the string value I want, but when I convert that to an int, I get a NumberFormatException
:
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.dcasillasappdev.mytrackfieldteam.utility.Utility.convertToDigits(Utility.java:333)
Am I missing something here? Thanks in advance!