Re: Operation in String to Double conversion
On 10/14/2012 3:39 PM, William Lopes wrote:
Hi guys!
So, I have to do a conversion between String and Double object, but my string is a mathematical operation like "100 + 10". Even when I make a conversion using NumberFormat.getInstance of "100 + 10", my result is 100.0 only.
I would like to do it without split my string of way manually.
I wrote an expression evaluator will accept such a string and
produce an object instance that can then be evaluated:
Expression e = Expression.compile("100 + 10", null);
double value = e.value(null);
More generally,
// Formula for volume of a cylinder:
Expression e = Expression.compile(
"(diameter/2)^2 * PI * height",
new String[] { "diameter", "height" });
// Volume of a cylinder of diameter 4, height 10:
double volume = e.value(new double[] { 4.0, 10.0 });
The only unusual feature is that expressions compile directly to
Java byte code rather than to an interpreted pseudo-code; their
value() methods can therefore be JITted for speedier execution.
This is surely overkill for your problem (and for many others;
it was an over-engineered learning exercise), but should solve it
nonetheless. Internally, though, the compiler splits the string
"of my way manually," which you seem to find distasteful. Sue me.
Send an E-mail address if you'd like a copy. No warranties.
--
Eric Sosman
esosman@comcast-dot-net.invalid