Reputation: 1864
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?
Upvotes: 2
Views: 490
Reputation: 7310
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.
Upvotes: 0
Reputation: 405765
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.
Upvotes: 2
Reputation: 9267
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"));
Upvotes: 4