Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate formula from string to int

I have a table that contains formula. Example of the formula:

(GP1/(GP1 + GP2))*100%.

In my code using jquery, i will replace GP1 with textbox1 value, GP2 with textbox2 value and remove the %.

I try to get the result by doing this:

var repl1 = (GP1/(GP1 + GP2))*100%;
var repl2 = repl1.replace(/GP1/gi,parseInt($("#txtbox1").val()));
var repl3 = repl2.replace(/GP2/gi,parseInt($("#txtbox2").val()));
var repl4 = repl3.replace(/%/gi,"");

==> so the last result will be:

 var repl4 = (10/(10+0))*100

I try to convert it to be int by doing this:

var result = parseInt(repl4);

But i get the result NaN.

Can anybody help me on how to calculate the formula

Thank you.

like image 202
eikaz Avatar asked Apr 07 '15 07:04

eikaz


People also ask

How do you convert a string containing an expression to an integer?

If the String contains only numbers, then the best way to convert the String to Int is by using Integer. parseInt() or Integer. valueOf() . If the String contains both numbers and characters, then we have to use regular expressions to extract numbers from the string and then convert the resulting String it to Int.

Can string be used for calculation?

You can't directly evaluate a String as a mathematical expression in Java (it's a compiled language). You'd have to write your own parser for that, which is actually quite a lot of work, and it also has already been done by other people.

Which variable expression correctly converts the string value's into an integer?

In Python, you can convert a string to an integer using the int() function.


1 Answers

What you are looking for is:

var result = eval(repl4)

Be careful however as any Javascript in repl4 will be evaluated and executed, i.e. if someone types malicious Javascript into your text field it will get executed unless you filter it.

Applying parseInt() to the values of the text input however make the use of eval() acceptable in your example as it will return an integer or NaN thus preventing any code injection (this assumes of course that the formula is not coming from an input as well).

like image 188
SGD Avatar answered Oct 17 '22 06:10

SGD