I am having a string which may have a value like 1000.021 which i then convert to double using the method below
double amount = Double.parseDouble(1000.021);
This just works fine when its a single decimal place but when i get a sting value like 1000.021.2344.455 it crashes on parsing the double from String to double how can i be able to remove the extra decimal places after the first one so the i have a double like 1000.0212344455 when i get a value like 1000.021.2344.455
Below is what i have tried but it just removes all the decimal places and it just accepts a number with a single decimal place in the .format
new DecimalFormat("#").format(100.22);
CodePudding user response:
Try the below code for the conversion:
public static double toDouble(String s) {
int i1 = s.indexOf(".");
return Double.parseDouble(s.substring(0, i1 1) s.substring(i1).replaceAll("\\.", ""));
}
Test case:
@Test
public void test(){
double v = toDouble("1000.021.2344.455");
assert v == 1000.0212344455;
}
CodePudding user response:
I just tried that one:
String str = "1000.021.2344.455";
String newStr = "";
boolean dot = true;
for (int i = 0; i < str.length(); i ) {
if (str.charAt(i) == '.' && dot) {
newStr =str.charAt(i);
dot =false;
}
if(str.charAt(i) != '.' || dot){
newStr =str.charAt(i);
}
}
Double num = Double.parseDouble(newStr);
System.out.println(num);
Output: 1000.0212344455