tags:

views:

125

answers:

3

Not sure how to word this and so am not having much luck in Google searches...

I need to calculate a value for a string of numbers.

Example. A user types in "1.00 + 2.00 - 0.50" into a text field. The function should be able to take that string and calculate the result to return $2.50.

Anyone have a way to do this in their bag of tricks?

+4  A: 

If it's actually a mathematical operation you may just use eval, not sure that's what you want though :

document.write(eval("1.00 + 2.00 - 0.50"));
Theo.T
If the input string had $ in it too you could simply do replace "$" with "" before passing it to eval
Brian R. Bondy
Good point, that was actually my only fear when I answered.
Theo.T
You'll probably want to do more validation than just replacing currency symbols.
Joel Coehoorn
+2  A: 

Theo T's answer looks like the most straightforward way, but if you need to write your own simple parser, you can start by splitting the string and looking for your operators in the output.

Bill the Lizard
+1 for linking to other's answers to their boxes :) Hint: do not include the full URL, just the part after the #. That way the link would be immediate instead of a full reload in some browsers ;)
Seb
@Seb: Thanks for the tip.
Bill the Lizard
A: 

New there had to be a simple super way to do it. That's exactly what I need, thanks!

Susan