Mjukis - 4 months ago 33

Javascript Question

I have this string:

`var sting = "500*500*500";`

Now i'd like to calculate the numbers in the string just as they are.

If i just had the numbers outside the string i could do math like:

`var sum = 500*500*500;`

console.log(sum) will return: 125000000

I found this question:

How to calculate numbers in string

Isn't there a easier way?

Like:

`var sum = calc(string);`

Answer

The best way is to use a Mathematic specialised eval function.

Make your own or simply use the awesome MathJS

```
// evaluate expressions
math.eval('sqrt(3^2 + 4^2)'); // 5
math.eval('sqrt(-4)'); // 2i
math.eval('2 inch to cm'); // 5.08 cm
math.eval('cos(45 deg)'); // 0.7071067811865476
```