Reputation: 459
I have an abstract class that contains a variable of type String declared moneyString
String moneyString;
It contains data something like $123,456,789
So inside the abstract class I have function
void convertToInt(){
remove(',');
remove('$');
empMoney = Integer.parseInt(moneyString.substring(0, moneyString.length()) );
}
And my remove function
void remove(char character){
boolean moreFound = true;
String tempString;
int index;
do{
index = moneyString.indexOf(character);
tempString = moneyString;
if(index!=-1){
//From beggining to the character
moneyString = moneyString.substring(0,index);
//After the character to the end
tempString = tempString.substring(index,tempString.length());
moneyString += tempString;
}
else{
moreFound = false;
}
} while(moreFound);
} //END remove()
Isn't it supposed to get out of the loop when when moreFound = false?
Upvotes: 1
Views: 73
Reputation: 1323
Indeed you have to change the line:
tempString = tempString.substring(index,tempString.length());
to:
tempString = tempString.substring(index+1,tempString.length());
The assignment could be done to a variable of type Long:
moneyString="$123,456,789,101";
long empMoney;
remove('$');
remove(',');
empMoney = Long.parseLong(moneyString.substring(0, moneyString.length()) );
Upvotes: 1
Reputation: 201447
The issue with your code is here,
tempString = tempString.substring(index,tempString.length());
Should be index + 1
because you don't want to include that character.
tempString = tempString.substring(index + 1,tempString.length());
But, I suggest you use a DecimalFormat
and parse(String)
the value. Like,
public static int convertToInt(String money) throws ParseException {
NumberFormat df = new DecimalFormat("$#,###");
return df.parse(money).intValue();
}
Then you can call it like
public static void main(String[] args) {
try {
System.out.println(convertToInt("$123,456,789"));
} catch (ParseException e) {
e.printStackTrace();
}
}
Output is
123456789
Upvotes: 3