1

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Mahesha Padyana
  • 431
  • 6
  • 22
  • 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
  • 1
    This can help you: http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Athanor Aug 05 '14 at 08:26

3 Answers3

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.

0

Use this :

 String s = "35/6";
 s = s.replace('/', '.');
 double d = Double.parseDouble(s);
Saman Gholami
  • 3,416
  • 7
  • 30
  • 71
-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);