How to convert a string equation to a numeric value using Javascript

Basically, I have a user input field in which the user can enter a number. They would also like to enter equations in the input field.

Something like "874.45 * 0.825 + 4000" is converted to its actual numerical value.

All solutions found point to the awful eval () method. Especially if this is a user input field, I just worry about starting eval ("874.45 * 0.825 + 4000") and hoping to get the number from the back.

I suppose I could make a web service call to a server (ASP.NET), but I'm afraid that a little delay will create some frustration from the user.

Does anyone know about good technology or existing libraries?

+4
source share
4 answers

What you really need is an "expression parser" because you are trying to allow users to express their values ​​using a small domain-specific language.

Basic mechanics works as follows:

  • Denote their expression in operators and operands.

  • Depending on the order of operations (for example, when multiplication is evaluated with a higher priority than adding), push operators and operands onto the stack.

  • Pull the operands from the stack and move the intermediate results back onto the stack. Repeat until the stack is empty.

I have done this gazillion times for different "small languages" in all my projects. But never in javascript. Therefore, I cannot directly recommend a suitable parsing library.

But a quick Google search reveals "PEG.js". Look at here:

http://pegjs.majda.cz/

All the examples in their documentation are designed specifically for what you are trying to create.

+4
source

Just multiply it by 1 and it will make javascript treat it as a whole from now on.

For instance,

int = '2343.34' * 1; int = input * 1; 
+1
source

And what is so bad in this case? eval ?

For me, this is great for your task. If you want to protect your execution context, you can define a function, for example:

 function calc(str) { var window = null, self = null, document = null; // other globals like: $ = null, jQuery = null, etc. try { return eval(str); } catch(e) {...} } 

and use it where you need to interpret the string. Simple and efficient.

+1
source

I think that eval can pose a lower security risk if you parse the resulting string and check its contents only as numbers and operators and evaluate by faking out external area variables such as a document, etc. like "var document = null".

+1
source

All Articles