I want to get value from web
For eg : Total AMount : 25000
and want to convert this value into integer to proceed comparision step but after printing totat_Amt it displayed as
"java.lang.NumberFormatException: For input string: "25,000""
Here is my code :
WebElement gt = driver.findElement(By.id("totAmt"));
String total_Amt=gt.toString();
System.out.println("Total Amt:"+total_Amt);
//int total_amt_val =Integer.parseInt(total_Amt);
System.out.println(total_amt_val);
Try to replace all non-numeric symbols:
WebElement gt = driver.findElement(By.id("totAmt"));
String total_Amt = gt.toString(); // "25,000"
// replace 'bad' symbols
String onlyNumbers = total_Amt.replaceAll("[^\\d]", ""); // "25000"
System.out.println("Total Amt: " + total_Amt);
int total_amt_val = Integer.parseInt(onlyNumbers); // 25000
System.out.println(total_amt_val);
\\d means all numbers, [^\\d] means all non-numbers, and if you want to keep some another symbols, just add them into [] — e.g. use [\\d.] if you want to keep dots too.
You can use NumberFormat
NumberFormat.getNumberInstance(Locale.US).parse("25,000").intValue() will return 25000
You can try this:
WebElement gt = driver.findElement(By.id("totAmt"));
String total_Amt = gt.toString(); // 25,000
total_Amt = total_Amt.replaceAll(",", ""); // removes all ',' -> 25000
int total_amt_val = Integer.parseInt(total_Amt); // 25000 as int already
System.out.println(total_amt_val); // 25000
You can replace all the comma first using replaceAll method and then directly parse it as below. additionally, you need to use getText() method should be used to retrieve the element text.
WebElement gt = driver.findElement(By.id("totAmt"));
//To be changed as gt.getText().
String total_Amt=gt.getText();
System.out.println("Total Amt:"+total_Amt);
//Replace comma as empty and then you can normal parse the string to int
int total_amt_val =Integer.parseInt(total_Amt.replaceAll(",",""));
System.out.println(total_amt_val)
In case , If you are getting the total_Amt value as Total AMount : 25000, then extract the amount value using substring method and then replace all the , as empty using replaceAll method
int total_amt_val =Integer.parseInt(total_Amt.substring(total_Amt.indexOf(":")+2).replaceAll(",",""));
If you are dealing with price, use this:
public static void main(String[] args) throws Exception {
WebElement gt = driver.findElement(By.id("totAmt"));
String total_Amt = gt.getText(); // total_Amt=25,000.00
BigDecimal bd_amt = parse(total_Amt , Locale.US); // Use this if the value is price
int int_amount = parse(total_Amt , Locale.US).intValueExact(); // Use this if you want integer
System.out.println("Price : " + bd_amt);
System.out.println("Amount : " + int_amount);
}
private static BigDecimal parse(final String amount, final Locale locale) throws ParseException {
final NumberFormat format = NumberFormat.getNumberInstance(locale);
if (format instanceof DecimalFormat) {
((DecimalFormat) format).setParseBigDecimal(true);
}
return (BigDecimal) format.parse(amount.replaceAll("[^\\d.,]", ""));
}
Sample Output:
Price : 25000.00
Amount : 25000
Related
I want to get the value from a string.
I have a string value like this:
String myData= "Number: 34678 Type: Internal Qty: 34";
How can I get the Number, Type, Qty values separately?
Give me any suggestion on this.
Input:
String myData= "Number: 34678 Type: Internal Qty: 34";
Output:
Number value is 34678
Type values is Internal
Qty value is 34
Here is one way to do it. It looks for a word following by a colon followed by zero or more spaces followed by another word. This works regardless of the order or names of the fields.
String myData = "Number: 34678 Type: Internal Qty: 34";
Matcher m = Pattern.compile("(\\S+):\\s*(\\S+)").matcher(myData);
while (m.find()) {
System.out.println(m.group(1) + " value is " + m.group(2));
}
You can use regex to do this cleanly:
Pattern p = Pattern.compile("Number: (\\d*) Type: (.*) Qty: (\\d*)");
Matcher m = p.matcher(myData);
m.find()
So you'll get the number with m.group(1), the Type m.group(2) and the Qty m.group(3).
I assume you accept a limited number of types. So you can change the regex to match only if the type is correct, for eg. either Internal or External: "Number: (\\d*) Type: (Internal|External) Qty: (\\d*)"
Here's a nice explanation of how this works
If you just want to print them with fixed pattern of input data, a simplest way is shown as follows: (Just for fun!)
System.out.print(myData.replace(" Type", "\nType")
.replace(" Qty", "\nQty")
.replace(":", " value is"));
I suppose the string is always formatted like that. I.e., n attribute names each followed by a value that does not contain spaces. In other words, the 2n entities are separated from each other by 1 or more spaces.
If so, try this:
String[] parts;
int limit;
int counter;
String name;
String value;
parts = myData.split("[ ]+");
limit = (parts.length / 2) * 2; // Make sure an even number of elements is considered
for (counter = 0; counter < limit; counter += 2)
{
name = parts[counter].replace(":", "");
value = parts[counter + 1];
System.out.println(name + " value is " + value);
}
This Should work
String replace = val.replace(": ", "|");
StringBuilder number = new StringBuilder();
StringBuilder type = new StringBuilder();
StringBuilder qty = new StringBuilder();
String[] getValues = replace.split(" ");
int i=0;
while(i<getValues.length-1){
String[] splitNumebr = getValues[i].split("\\|");
number.append(splitNumebr[1]);
String[] splitType = getValues[i+=1].split("\\|");
type.append(splitType[1]);
String[] splitQty = getValues[i+=1].split("\\|");
qty.append(splitQty[1]);
}
System.out.println(String.format("Number value is %s",number.toString()));
System.out.println(String.format("Type value is %s",type.toString()));
System.out.println(String.format("Qty value is %s",qty.toString()));
}
Output
Number value is 34678
Type value is Internal
Qty value is 34
I am trying to convert a string 32,646,513.32 to a double and then convert it to a string in scientific notation like this 3.264651332E7. The code below is
double amount = 0;
for (Payments payments : pvor.getPayments()) {
payments.setDocumentNumber(pvor);
amount += Double.parseDouble(payments.getAmount());
payments.setDate(new Date());
}
DecimalFormat df = new DecimalFormat("#.00");
double totalAMount = Double.valueOf(df.format(amount));
Double totalAMounts = (Double) totalAMount;
pvor.setAmount(String.valueOf(totalAMounts.doubleValue()));
How do I display large numbers in same format as I give?
Instead of using just String.valueOf(totalAmounts), which give you number in exponential format, you need to format your double value to match the string format that you want. Try something like new DecimalFormat("#,###.00").format(totalAmounts). Or simply use String.format("%,.2f", totalAMounts).
If I understood your problem correctly then you do not need String.valueOf() but String.format().
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String input = "32,646,513.32";
double value = Double.parseDouble(input.replace(",",""));
String output = String.format("%f",value);
System.out.println("Value: " + output);
}
Output:
Value: 32646513.320000
Replace the following line in your code appropriately:
/* Note the change from `valueOf()` to `format()` */
pvor.setAmount(String.format("%f",totalAMounts.doubleValue()));
I was wondering if someone can show me how to use the format method for Java Strings.
For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
System.out.println(String.format("%-20s= %s" , "label", "content" ));
Where %s is a placeholder for you string.
The '-' makes the result left-justified.
20 is the width of the first string
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
If you want a minimum of 4 characters, for instance,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.
#Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
For decimal values you can use DecimalFormat
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
and output will be:
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
I can have this string as below :
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
or
String s = "chapterId=c_1§ionId=s_24666";
I need to get the number ("24666" in the examples).
String res = s.substring(s.lastIndexOf("s_")+ 2) this returns me the number + chars till the end of the string(the second example is ok). But I need to stop after the number ends. How can I do that.? Thanks
You can use regExp
String s = "chapterId=c_1§ionId=s_24666";
//OR
//String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*?s_(\\d+).*","$1");
System.out.println(s);
OUTPUT:
24666
Where,
.*?s_ means anything before s_ (s_ inclusive)
(\\d+) means one or more digits () used for group
$1 means group 1 which is digits after s_
Note:Assumed that your every string follows specific format which includes s_ and number after s_.
You can split the string by the character & to get the parameters, and split each parameter with the = to get the parameter name and parameter value. And now look for the parameter name "sectionId", and cut the first 2 characters of its value to get the number, and you can use Integer.parseInt() if you need it as an int.
Note that this solution is flexible enough to process all parameters, not just the one you're currently interested in:
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
String[] params = s.split("&");
for (String param : params) {
String[] nameValue = param.split("=");
if ("sectionId".equals(nameValue[0])) {
int number = Integer.parseInt(nameValue[1].substring(2));
System.out.println(number); // Prints 24666
// If you don't care about other parameters, this will skip the rest:
break;
}
}
Note:
You might want to put Integer.parseInt() into a try-catch block in case an invalid number would be passed from the client:
try {
int number = Integer.parseInt(nameValue[1].substring(2));
} catch (Exception e) {
// Invalid parameter value, not the expected format!
}
Try this:
I use a check in the substring() method - if there is no "&isHL" in the string (meaning its type 2 you showed us), it will just read until the string ends. otherwise, it will cut the string before the "&isHL". Hope this helps.
Code:
String s = "chapterId=c_1§ionId=s_**24666**";
int endIndex = s.indexOf("&isHL");
String answer = s.substring(s.lastIndexOf("s_") + 2, endIndex == -1 ? s.length() : endIndex);
Try following:
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
String tok[]=s.split("&");
for(String test:tok){
if(test.contains("s_")){
String next[]=test.split("s_");
System.out.println(next[1]);
}
}
Output :
24666
Alternatively you can simply remove all other words if they are not required as below
String s="chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*s_(\\d+).*","$1");
System.out.println(s);
Output :
24666
The dig over here is splitting your string using a Regular Expression to further divide the string into parts and get what is required. For more on Regular Expressions visit this link.
You could sue this regex : (?<=sectionId=s_)(\\d+) This uses positive look-behind.
demo here
Following code will work even if there is multiple occurrence of integer in given string
String inputString = "chapterId=c_a§ionId=s_24666&isHL=1&cssFileName=haynes_45";
String[] inputParams = inputString.split("&");
for (String param : inputParams)
{
String[] nameValue = param.split("=");
try {
int number = Integer.parseInt(getStringInt(nameValue[1]));
System.out.println(number);
}
catch(IllegalStateException illegalStateException){
}
}
private String getStringInt(String inputString)
{
Pattern onlyInt = Pattern.compile("\\d+");
Matcher matcher = onlyInt.matcher(inputString);
matcher.find();
String inputInt = matcher.group();
return inputInt;
}
OUTPUT
2466
1
45
Use split method as
String []result1 = s.split("&");
String result2 = tempResult[1];
String []result3 = result2.split("s_");
Now to get your desire number you just need to do
String finalResult = result3[1];
INPUT :
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
OUPUT :
24666
I was wondering if someone can show me how to use the format method for Java Strings.
For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
System.out.println(String.format("%-20s= %s" , "label", "content" ));
Where %s is a placeholder for you string.
The '-' makes the result left-justified.
20 is the width of the first string
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
If you want a minimum of 4 characters, for instance,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.
#Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
For decimal values you can use DecimalFormat
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
and output will be:
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html