Jayden Ng
Jayden Ng

Reputation: 151

How to split the string only get a particular value

I have a string, "900.9/6.00%", that I want to split into string only get particular value of "6.00" while taking particular value of "6.0" multiply by 2 of bettingAmount.

 bettingAmount : 2.000
 bettingAmount : 900.9/6.00%

My Code :

String string = "900.9/6.00%";
String[] parts = string.split("/");
String part1 = parts[0]; // 900.9
String part2 = parts[1]; // 6.00%

That means the first string will contain the characters before '/', and the second string will contain the characters after '/'. But the problem is i need to get the value only "6.0". How can I do this? Kindly advise

Upvotes: 0

Views: 926

Answers (6)

Sigja
Sigja

Reputation: 93

Have you tried:

part2 = part2.replace("%", "");

It replaces the % with nothing.

Then as Joop suggests you can do:

double pct = Double.parseDouble(part2);

Upvotes: 1

Jayden Ng
Jayden Ng

Reputation: 151

Thanks to @codechat ,

I have amend the code to get the result of 0.12

double result=Double.parseDouble(part6.substring(part6.indexOf("/")+1,part6.indexOf('%')))*2/100.0;
        System.out.println(" result "+result); // result 0.12

Upvotes: 0

Saurabh Chaturvedi
Saurabh Chaturvedi

Reputation: 2166

A substring based solution

String xy="900.9/6.00%";
double result=Double.parseDouble(xy.substring(xy.indexOf("/")+1,xy.indexOf('%')))*2;
System.out.println(" result "+result); // result 12.0

same code:

String xy="900.9/0.06%";
double result=Double.parseDouble(xy.substring(xy.indexOf("/")+1,xy.indexOf('%')))*2;
System.out.println(" result "+result); // result 0.12

Upvotes: 4

Thomas Betous
Thomas Betous

Reputation: 5123

I think can do this with a regex, but it may a little bit complicated :

String REGEX = "^(\\d+\\.\\d+)/(\\d+\\.\\d+)";
String string = "900.9/6.00%";
String part1 = "";
String part2 = "";

Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(string);
if(m.find()){
        MatchResult mr = m.toMatchResult();
        part1 = mr.group(1)
        part2 = mr.group(2)
}

Otherwhise you can just remove "%" before to split your string :

String string = "900.9/6.00%";
string = string .replace("%", "");

Upvotes: 0

Luca Nicoletti
Luca Nicoletti

Reputation: 2427

String valuetoSave = string.split("/")[1]
//valuetoSave = "6.00%"
valuetoSave = valuetoSave.split("%")[0]
//valuetoSave = "6.00"

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109597

String[] parts = string.split("[/%]");

Splits on any char / or %.

double pct = Double.parseDouble(part2);
pct *= 2; // or such

Upvotes: 1

Related Questions