0

I need to convert a string, such as "12 / 4", into a double value. I may not be explaining it well but I am sure you can see what I am trying to do.

I haven't tried much since I don't have much of a clue what I need to do :(.

public static double evaluateString(String str){
    double value;

    // Some code

    return value
}

If str = "12 / 4", I want the value to return 3.

Jake Jackson
  • 1,055
  • 1
  • 12
  • 34
  • https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form if you are asking about equations in general or is this only for division? – Joakim Danielson May 08 '19 at 10:11
  • You can parse the string using a stack. Visit https://stackoverflow.com/questions/24725374/java-postfix-calculator-push-pop-method-with-a-string-array – Yunus Kerem Türk May 08 '19 at 10:13

2 Answers2

1

I think that you could use mXparser library for Java:

http://mathparser.org/

You can create an Expression and evaluate it for getting result.

manuelcr
  • 43
  • 6
-2

There are Double API's valueOf which you can use it for conversion. But you have to handle the exception if its not a number(integer/double)

static Double valueOf(String s) Returns a Double object holding the double value represented by the argument string s.

Shriram
  • 4,343
  • 8
  • 37
  • 64