2

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?

3 Answers 3

4

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"));
Sign up to request clarification or add additional context in comments.

2 Comments

If the input string had $ in it too you could simply do replace "$" with "" before passing it to eval
You'll probably want to do more validation than just replacing currency symbols.
2

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.

1 Comment

+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 ;)
0

Just to improve Theo's answer.

You should NOT be using eval unless you're absolutely sure what you are passing to that function. Since eval will run the code, you can write any JavaScript code and it will be executed.

One of the ways of making sure you will only get the right code is using the following script:

var str = "$34.00 + $25.00 alert('some code')"; // Our string with code
var pattern = /[0-9\+\-\.\*\/]*/g; // Regex pattern
var math_operation = str.match(pattern).join(''); // Getting the operation
document.write(eval(math_operation));​ // Getting the result

This not only allows the user to type things like $34.00 + $5.00 but also prevents from code being injected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.