How do split only numbers from a given string of "$##,##,###.###" in JAVA - java

I am stuck with a problem of splitting just the numbers from a given input string
take an example of a total bill of
TOTAL = $19,67,456.45
Now, for the arithmetic calculations we need just the numbers removing the
$ , .
and so every string which tries to come in the entire string of
TOTAL=$##,##,##,###
Finally we should have just the numbers for performing arithmetic calculations on bill.
I tried to solve this as follows
String price = "$12,23,44,555"
String ArrArgs[] = price.split("");
for (int i=2;i<ArrArgs.length;i++){
if (ArrArgs.equals(".")){
break;
}
if ((ArrArgs[i]).equals(",")){
}else {
strPrice = ""+strPrice+ArrArgs[i];
System.out.println("Adding "+ArrArgs[i]);
}
}
BTW All I am doing is to automate a testcase in Selenium WebDriver for bills greater than $99,99,99,999.
Thank you in advance :)

do like this
NumberFormat format = NumberFormat.getCurrencyInstance();
Number number = format.parse("$19,67,456.45");
System.out.println(number.toString());
Output
1967456.45

Try it with the String.replaceAll function:
String TOTAL = "$19,67,456.45";
System.out.println(TOTAL.replaceAll("[\\$,.]", ""));
The function takes a regular expression.

Related

How to remove one letter in Jsoup?

I am having troubles with parsing string into double. I am trying to get the price of an item but the string returns in a value like: $24.54. So the problem (I'm assumming) is that it is conflicting with the $. Is there a way to eleminate the $ and turn the 24.54 into a double and store in a variable. Here is the code: (PS I am a C++ programmer haven't programmed in Java for a while so feel free to give me tips):
Elements tdsInSecondRow = doc.select("table tr:eq(1) > td:eq(0)"); //Test the changing of these numbers
Elements prices = doc.select("table tr:eq(1) > td:eq(2)");
for (Element td : tdsInSecondRow)
{
String word = td.text(); //Saved the text into symbol
double price = Double.parseDouble(prices.text());
System.out.println(symbol);
System.out.println(price);
}
You could check if your text starts with "$".
if(word.startsWith("$")){
word = word.substring(1, word.length());
}
double price = Double.parseDouble(word.text());
Hope it helps,

Java input/output confusion

I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.

How to print a string with an int

I am trying to get this code to run and basically solve an equation. So, I asked the user to write an equation. It looked like this:
System.out.println("Write an equation and I will solve for x.");
int answer = in.nextLine();
But I can't get the user to write a string and an int. Do I need to say String answer or int answer?
An int is used when you want the user to enter a number, but here you're looking for a combination of numbers and other characters, so you will need to use a string. When you have the equation stored in a string, you can use other methods to split up the equation into something solvable, then set int answer to whatever the answer comes out to be.
On a simpler side, String will be required input from the user, User will enter the equation.
Then comes the complex part of solving/computing the equation.
1.) create your own parser to pass operands/operator.
2.) Provide a equation with values to some API, you can make use of MVEL or ANTLR
Here's a little program that demonstrates one way to get the equation and divide into numeric / non-numeric values provided the equation input is space delimited. You can then determine what the non-numeric values are and proceed from there.
import java.util.Scanner;
public class SolveX{
public static void main(String[] a){
Scanner in = new Scanner(System.in);
System.out.println("Write an equation and I will solve for x.");
String input = "";
while( in.hasNext() ){
input = in.next();
try{
double d = Double.parseDouble(input);
System.out.println("Double found at: " + input);
// Do what you need to with the numeric value
}
catch(NumberFormatException nfe){
System.out.println("No double found at: " + input);
// Do what you need to with the non numeric value
}
}
}//end main
}//end SolveX class

Java Remove all cases of .0

I want a filter to run through a string and eliminate all of the un-needed .0's from the doubles. I have already tried replaces, but cases like 8.02 turn into 82.
I have a feeling this has been done before, but I cannot find any help.
I am looking for a method that will take in a String, example: "[double] plus [double] is equal to [double]", where the [double] is a double that will need to be checked for the redundant decimal.
Thanks in advance!
let's say you have a string called s that contains text like you described. simply do:
s = s.replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2");
and you're done.
ok, so i edited this a couple of times. now it works though!
You can do this with a java.text.DecimalFormat object.
Can you not take away the trailing zeros before you construct them into your string? This way you could use the DecimalFormatter method someone posted earlier and then deleted.
NumberFormat formatter = new DecimalFormat("0.##");
String str = formatter.format("8.0200");
System.out.println(str);
Give them credit for the code if they come back.
The other posts assume you're working with a short string containing only decimal.
Assuming you're working with large strings of text, you can use Pattern/Matcher classes (I'm at work, so posting in a hurry. Check for errors)
Use this regex to replace:
/* >1 digits followed by a decimal and >1 zeros. Note capture group on first set of digits. This will only match decimals with trailing 0s, and not 8.0002 */
(\d+)\.0+
Replace with
/* First capture group */
$1
I'm unsure of the regex rules for Java, so use this as a concept to get what you want.
The following program will remove all trailing zeros from the fractional part of a double value. If your requirements are somewhat different, you may need to modify it slightly.
final public class Main
{
public static void main(String...args)
{
System.out.println("Enter how many numbers you want to check:->");
Scanner scan = new Scanner(System.in);
final double KEY_VALUE = 0.0;
final Double TOLERANCE = 0.000000000001d;
int n = scan.nextInt();
double[] a = new double[n];
for (int i = 0; i < n; i++)
{
a[i] = scan.nextDouble();
}
List<Double> newList = new ArrayList<Double>();
for (int k = 0; k < n; k++)
{
if (Math.abs(a[k] - KEY_VALUE) < TOLERANCE)
{
continue;
}
newList.add(a[k]);
}
System.out.println(newList);
}
}
You can specifically use DecimalFormat to truncate the specified number of decimal places, if you need such as follows.
double x=10.4555600500000;
DecimalFormat df=new DecimalFormat("#.##");
System.out.println(df.format(x));
Would return 10.46.

Conversion of string numbers into comma seperated string numbers in Android

I am currently working on an Android project where we use string numbers with many digits in it.
So I want to know whether there is a way to convert the string numbers for e.g 1000000000 into comma separated string numbers for e.g(1,00,00,00,000) in Indian Locale format.
I got the US locale format string conversion but I want Indian locale format.
I would use format("% ,d", number) method of Format class, ensuring that I initialize the Formatter object with the appropriate locale (which I believe is en_IN for Indian).
Having said that, it would be easier for people to help you if you posted code on how you are doing it for US locale in the first place.
Ref : Formatting a Number Using a Custom Format
private String getFormatedData(String unformatedData) {
if(unformatedData != null) {
try {
//unformatedData.replaceAll(",", "");
Double result = Double.valueOf(unformatedData);
DecimalFormat myFormatter = new DecimalFormat("###,##0.00");
//DecimalFormat myFormatter = new DecimalFormat("#,###,###");
//If you don't want to show .00 format
return myFormatter.format(result);
} catch (NumberFormatException e) {
return unformatedData;
}
} else {
return "0.00";
}
}
Use this method.
I think you have to modify this method if you don't need .00 value. Let me work on it.
I think that you need to use NumberFormat so you can make a general case using current Locale settings of the user.
And I think that this is your current situation:
If you are formatting multiple numbers, it's more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.
NumberFormat nf = NumberFormat.getInstance();
for (int i = 0; i < a.length; ++i) {
output.println(nf.format(myNumber[i]) + "; ");
}
The answer given by Pankaj Kumar gives the output in US format not in Indian Format.
If you want in US format it can be easily done by following code:
NumberFormat.getNumberInstance(Locale.US).format(35634646)
As shown here: Converting Integer to String with comma for thousands
To get the string with commas in Indian Format you can try this manual code
public String round(String d)
{
ArrayList<Integer> commas=new ArrayList<Integer>();
String output=null;
char[] preDecimal=d.split("[.]")[0].toCharArray();
int i=preDecimal.length-3;
System.out.println(i);
while(i>0)
{
commas.add(i);
i-=2;
}
StringBuilder sb=new StringBuilder();
for(i=0;i<preDecimal.length;i++)
{
sb.append(preDecimal[i]);
if(commas.contains(i+1))
sb.append(",");
}
output=sb.toString();
return output;
}

Categories

Resources