Master Selenium, Java & Web Automation + Selenium Live Projects
Next Selenium Training Batch Starts on 23 Oct ENROLL NOW @ 50% OFF - 3 Days Left

How to get a number (int or double) from a string message in Java?

 

JAVA Code

public class ExtractIntAndDouble {

public static void main(String[] args) {

 

//*************** Extracting int values *************************

String searchCountStr = "There are 280 search results";
// or String cartCountStr = "There are total 6 items in your cart";

int searchCount = Integer.parseInt(searchCountStr.replaceAll("\\D", ""));

System.out.println(searchCount);

 

//*************** Extracting double values *************************

String totalPriceStr = "Your have paid £154.75 for this order";
// or String totalPriceStr = "Total Price: £154.75";

double totalPrice = Double.parseDouble(totalPriceStr.replaceAll("[^0-9\\.]+", ""));

System.out.println(totalPrice);

}

}

In searchCountStr.replaceAll("\\D", ""), "\\D" is a regular expression to represent all non-digit characters and "" represents blank string. searchCountStr.replaceAll("\\D", "") gives string with only digits like "280" by replacing all non-digit characters with blank string.

In totalPriceStr.replaceAll("[^0-9\\.]+", ""), "[^0-9\\.]+" is a regular expression to represent all characters except digits 0-9 and dot character (.). Also, "" represents blank string. totalPriceStr.replaceAll("[^0-9\\.]+", "") gives string with only double value like "154.75" by replacing all characters with blank string except digits 0-9 and dot character (.) .

This is more effective than using split function (mentioned below) as we don't need to worry about our int or double value position and  currency symbols before price values

String[] tempArray = searchCountStr.split(" ");
int searchCount = Integer.parseInt(tempArray[2]);
System.out.println(searchCount);

The above code will work for string "There are 280 search results" but will not work for string "There are total 6 items in your cart". This is because int value position changes in both strings.

 

Want to ask a question - Contact Us!

 

Starting & Growing Your Career is EASY!

Close

50% Complete

Two Step

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.