public class StringCommaSuppresser {
public static void main(String[] args) {
System.out.println(formatToValue("5,000,000"));
}
public static Double formatToValue(String amount) {
String tempAmount = amount;
Double amnt = 0.0;
try{
if (tempAmount.contains(",")) {
amount = "";
do {
amount = amount.concat(tempAmount.substring(0, tempAmount.indexOf(",")));
tempAmount = (tempAmount.substring(tempAmount.indexOf(",") + 1));
} while (tempAmount.contains(","));
amount = amount.concat(tempAmount);
}
if (amount != null && !("").equals(amount)) {
amnt = Double.parseDouble(amount);
}
return amnt;
} catch(NumberFormatException e){
return 0.0;
}
}
}
Output:5000000.0
The above approach is a primitive way of doing things. We can better implement the same functionality in a efficient way like
public static Double formatToValue(String amount) {
try{
Double resultantAmount = null;
if (amount != null && !(ApplicationConstants.COMMON_EMPTYSTRING).equals(amount) && amount.contains(",")) {
String result = amount.replaceAll(",","");
resultantAmount = Double.valueOf(result);
}else if(amount != null && !(ApplicationConstants.COMMON_EMPTYSTRING).equals(amount) && !amount.contains(",")) {
resultantAmount = Double.valueOf(amount);
}
return resultantAmount;
}catch(NumberFormatException e){
return 0.0;
}
}
class ApplicationConstants {
public static final String COMMON_EMPTYSTRING="";
}