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.
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.
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.
In Python, you can convert a string to an integer using the int() function.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With