Is it possble to convert a string in a/b format to double in Java? Ex: str = "4/5"; Can I parse this and get float/double value? I used parseDouble, but did not work and it expects something like "34.33" as input string.
Asked
Active
Viewed 541 times
1
-
What you want is to evaluate the math expression and then parse the result to a double. There are libraries for evaluating a math expression in a string format, or you can write your own method for it. – Daniel B Aug 05 '14 at 08:26
-
1This can help you: http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Athanor Aug 05 '14 at 08:26
3 Answers
2
If your expression is always of the type "a/b" you can try something like:
String str = "4/5";
String parts[] = str.split("/");
double res = Double.parseDouble(parts[0])/Double.parseDouble(parts[1]);
Otherwise, use an expression evaluation tool as suggested in the comments above.

Pablo Francisco Pérez Hidalgo
- 27,044
- 8
- 36
- 62
0
Use this :
String s = "35/6";
s = s.replace('/', '.');
double d = Double.parseDouble(s);

Saman Gholami
- 3,416
- 7
- 30
- 71
-
1I think the OP wants to evaluate `4/5` and save its double value. You are proposing to use `/` as decimal separator token. I don't think that is right. Your code will result in `d = 35.6` whereas it should be `d = 5.83` – Pablo Francisco Pérez Hidalgo Aug 05 '14 at 08:32
-
-1
In javascript, you can use function "eval" to do it.But in Java,there is no function like that.So you use ScriptEngine to do it in java.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine se = manager.getEngineByName("js");
String str = "4/5";
Double result =(Double) se.eval(str);
System.out.println(result);

userFromEast
- 63
- 5