calculate string value in javascript

Solutions on MaxInterview for calculate string value in javascript by the best coders in the world

showing results for - "calculate string value in javascript"
Juana
08 Oct 2019
1<div>
2  <label for="input">Equation: </label>
3  <input type="text" id="input" value="12/5*9+9.4*2-1" />
4  <input type="button" 
5         value="calculate" 
6         onclick="getElementById('result').value = calculate(getElementById('input').value)" />
7</div>
8
9<div>
10  <label for="result">Result: </label>
11  <input type="text" id="result" />
12</div>
Anastasia
29 Jul 2016
1function calculate(input) {
2
3  var f = {
4    add: '+',
5    sub: '-',
6    div: '/',
7    mlt: '*',
8    mod: '%',
9    exp: '^'
10  };
11
12  // Create array for Order of Operation and precedence
13  f.ooo = [
14    [
15      [f.mlt],
16      [f.div],
17      [f.mod],
18      [f.exp]
19    ],
20    [
21      [f.add],
22      [f.sub]
23    ]
24  ];
25
26  input = input.replace(/[^0-9%^*\/()\-+.]/g, ''); // clean up unnecessary characters
27
28  var output;
29  for (var i = 0, n = f.ooo.length; i < n; i++) {
30
31    // Regular Expression to look for operators between floating numbers or integers
32    var re = new RegExp('(\\d+\\.?\\d*)([\\' + f.ooo[i].join('\\') + '])(\\d+\\.?\\d*)');
33    re.lastIndex = 0; // take precautions and reset re starting pos
34
35    // Loop while there is still calculation for level of precedence
36    while (re.test(input)) {
37      output = _calculate(RegExp.$1, RegExp.$2, RegExp.$3);
38      if (isNaN(output) || !isFinite(output)) 
39        return output; // exit early if not a number
40      input = input.replace(re, output);
41    }
42  }
43
44  return output;
45
46  function _calculate(a, op, b) {
47    a = a * 1;
48    b = b * 1;
49    switch (op) {
50      case f.add:
51        return a + b;
52        break;
53      case f.sub:
54        return a - b;
55        break;
56      case f.div:
57        return a / b;
58        break;
59      case f.mlt:
60        return a * b;
61        break;
62      case f.mod:
63        return a % b;
64        break;
65      case f.exp:
66        return Math.pow(a, b);
67        break;
68      default:
69        null;
70    }
71  }
72}
Lacy
18 Jan 2021
1label {
2  display: inline-block;
3  width: 4em;
4}
Blaze
02 Sep 2020
1let res2 = (new Function('return '+str)())