1

i'm working in android and I need your help. In string in values I have this

<item>(1 / 1024)</item>

I need to parse this string to double this way

outputDouble = Double.parseDouble(unitsValues[outputPosition]);

so it means this

outputDouble = Double.parseDouble((1 / 1024));

This second code mean, that I find the line by index I need and it tries to convert it from string to double but it is impossible because it can recognize this string (1 / 1024) to double. Do you have any ideas?

Thank you

  • 1
    Very similar to the following questions: http://stackoverflow.com/questions/3422673/java-evaluate-string-to-math-expression – sean Jul 08 '12 at 07:51
  • android doesnt support ScriptEngineManager package, so there is a problem – user1501722 Jul 08 '12 at 07:59

3 Answers3

1

There is no built in method to do that ... However you could do that with an external library like BeanShell :

Interpreter interpreter = new Interpreter();
interpreter.eval("(1 / 1024)");

To use Beanshell with Android, download the bsh-core.jar file, put it in a /lib folder in your project, and adjust your Eclipse settings or Ant script to reference that JAR during compilation and packaging.

aleroot
  • 71,077
  • 30
  • 176
  • 213
0

Maybe this will illustrate you how to do the parsing using the String#split. There is no direct method to do the conversion.

String representation = getString(R.string.my_repr);
String [] splits  = representation.split("/");
Double num = Double.valueOf(splits[0].trim()) / Double.valueOf(splits[1].trim());

EDIT I also added trimming to the strings, because of the danger of spurious interval symbols.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • and If I have more complicated code like (1/(1024 * 1024)) and so on? – user1501722 Jul 08 '12 at 08:06
  • Read about the Interpreter design pattern (http://en.wikipedia.org/wiki/Interpreter_pattern). Better if you find the Gang of Four book (http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612), not the wikipedia stuff. – Boris Strandjev Jul 08 '12 at 08:11
0

Using regex parse (1 / 1024) into two Double values 1f and 1024f and then divide them to get a Double value.

Aqif Hamid
  • 3,511
  • 4
  • 25
  • 38
  • ok, very easy idea, but it takes a time until a resolve the examples like (1/(1024 * 1024)), (1/(1024 * 1024 * 1024)) and so on – user1501722 Jul 08 '12 at 08:05