Java – How to convert a string of a specific format to double

How to convert a string of a specific format to double… here is a solution to the problem.

How to convert a string of a specific format to double

I’m using getText() to get a string from xpath. The string is “500.00/=” and now I want to convert it to double so that I can add it, but the problem is that when I use getText() I also get “/=”, so how to exclude this extra string format

Gets the amount as a string

String actualbookfees_amount = driver.findElement(By.xpath("//[@id='charges']/table[2]/tbody/tr[1]/td[2]")).getText();

String WHT_amount= driver.findElement(By.xpath("//[@id='charges']/table[2]/tbody/tr[2]/td[2]")).getText();

String numPlate_amount = driver.findElement(By.xpath("//[@id='charges']/table[2]/tbody/tr[3]/td[2]")).getText();

String registrationfees_amount= driver.findElement(By.xpath("//[@id='charges']/table[2]/tbody/tr[4]/td[2]")).getText();

String Motor_vehicle=driver.findElement(By.xpath("//*[@id='charges']/table[2]/tbody/tr[5]/td[2]")).getText();

String With_amount=driver.findElement(By.xpath("//*[@id='charges']/table[2]/tbody/tr[5]/td[2]")).getText();

converting amount in integers
double actualbookfees_amount_int = Double.valueOf(actualbookfees_amount);
double WHT_amount_int = Double.valueOf(WHT_amount);
double numPlate_amount_int = Double.valueOf(numPlate_amount);
double registrationfees_amount_int = Double.valueOf(registrationfees_amount);
double Motor_vehicle_int = Double.valueOf(Motor_vehicle);
double With_amount_int = Double.valueOf(With_amount);

double total_amount_int= actualbookfees_amount_int + WHT_amount_int+numPlate_amount_int+ registrationfees_amount_int+Motor_vehicle_int+With_amount_int;
System.out.println(total_amount_int);

Solution

You can do this by replacing “.

String actualbookfees_amount = "100,000.00 /=";

actualbookfees_amount = actualbookfees_amount.replace(",", "");
double actualbookfees_amount_int = Double.valueOf(actualbookfees_amount.substring(0, actualbookfees_amount.length()-2));
System.out.println(actualbookfees_amount_int);

Related Problems and Solutions