0

How to convert this string:

String str = "***123.45***";

to this double:

double d = 123.45; 

When I use valueOf

double d = Double.valueOf("***123.04***");

or parseDouble

double d = Double.parseDouble("***123.45***");

it will throw java.lang.NumberFormatException: For input string: ""123.04"" because the string doesn't contain number only. I need to get rid of the asterisks.

1
  • Two questions: 1. Are there always 3 before and 3 after the double? And 2. Are they always *, or can it also be another character (like letters)? Commented Nov 3, 2014 at 14:53

3 Answers 3

1

Try replace api to replace all "*" in your input as below:

double d = Double.valueOf("***123.04***".replace("*", ""));
System.out.println(d);
Sign up to request clarification or add additional context in comments.

1 Comment

There is no need to use replaceAll, replace works too and OP doesn't have to care about escaping that asterisk.
1

delete the asterixes before

str = str.replace("*", "");

2 Comments

This is not going to work unless and until you escape "*". you know wildcard character how they are :)?
.replaceAll uses a regex, so it should be either str.replace("*", ""); or str.replaceAll("\\*", "");
0

Try using regex to match the number:

String s = "eXamPLestring>1.4365345>>ReSTOfString";
Pattern p = Pattern.compile("\\D*([0-9]*\\.*[0-9]*)\\D*");
Matcher m = p.matcher(s);
if (m.find()) {
    System.out.println(Double.parseDouble(m.group(1)));

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.