1

I am storing a value in a DB (called generalparameter).

This value is a calculation which I call in the JS code.

The issue is the value is a string but I want it to be a calculation value.

e.g. My DB value is:-

(((this.amount / new_rate) - this.stock_payment).toFixed(2) / (this.amount / new_rate) * 100).toFixed(2)

My code is:-

application.getGeneralParameter('UI','CAL_NEW_MARGIN');

But this yields:-

"(((this.amount / new_rate) - this.stock_payment).toFixed(2) / (this.amount / new_rate) * 100).toFixed(2)"

How do I get rid of the ""?

Thanks.

Ian.

3
  • 1
    Evil eval will help you Commented Jul 10, 2015 at 8:31
  • What database and what server language? You should be able to remove the quotes on the server. Commented Jul 10, 2015 at 8:34
  • Like other comments and answers said, eval() is your solution, but be carefull with eval() function, it's unsafe. And it is not good practice to store code like this in database, it's better if you store in db a flag or a identifier that calls the string in the code. It's only a recommendation. Good luck Commented Jul 10, 2015 at 8:37

2 Answers 2

2

This works without the actual eval keyword - Function will however also evaluate so caution is advised if arbitrary strings can be saved in the DB since it will execute in the scope of the website your are on.

var fnString = "(((this.amount / new_rate) - this.stock_payment).toFixed(2) / (this.amount / new_rate) * 100).toFixed(2)",
obj = {
  amount:3.9,
  stock_payment:42,
  calc : Function("var new_rate=6.9; return "+fnString)
}
alert(obj.calc())

Sign up to request clarification or add additional context in comments.

2 Comments

Not sure whether new Function is much better than eval :-) It only works if new_rate is a global variable, for example.
@Bergi - moved new_rate to the function and added an advisory caution.
0

Try using the eval() function, like so:

eval("(((this.amount / new_rate) - this.stock_payment).toFixed(2) / (this.amount / new_rate) * 100).toFixed(2)");

or like so:

eval(application.getGeneralParameter('UI','CAL_NEW_MARGIN'));

1 Comment

Thanks for the suggestions. eval works, but might not be suitable due to injection issues etc, so I will proceed with care.

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.