I am building a conversion calculator. I would like to store the references and formulas for the calculator in JSON.
I do not know how to "process the variable as math".
JSON
var JSON = {
"conversions": [{[
{
"FromType": "in3",
"ToType": "ft3",
"Math": "/1728",
"Description": "divide the volume value by 1728"
}...
With the "Math" being done something like this.
D1 = document.getElementById("data1").value;
var theAnswer = eval(D1 conversions[0].Math);
Example:
D1 = 25
theAnswer = D1 /1728
theAnswer = 0.0144675
Is this possible? Is there a better way?
2
Answers
I had previously looked at Mathjs.. But, this is the route I went:
Screen:
A Json Example:
Then I loop the Json to find the "FromType" and "ToType" based on what the user selects in a select drop down:
It is probably not as succinct as it could be, but it is working really well so far for conversions for mass, distance, pressure, etc...
looks like you are trying to achieve while using eval() can work.
I won’t recommend it because of security reasons. A better approach would be to use a safer method to process.
Here is my suggestion:
use a library like
It is simple use the ‘mathjs’ library in the project, here is the path
Then, we can use the library to evaluate math expressions.