Sometimes, we want to evaluate a string as a mathematical expression in JavaScript.
In this article, we’ll look at how to evaluate a string as a mathematical expression in JavaScript.
How to evaluate a string as a mathematical expression in JavaScript?
To evaluate a string as a mathematical expression in JavaScript, we can use the mathjs
library.
To install it, we run
npm install mathjs
Then we can use it by writing
import { evaluate } from "mathjs";
const n = evaluate("1.2 * (2 + 4.5)");
to call evaluate
with the math expression we want to evaluate.
The return value is the value of the expression after evaluating as a number.
Conclusion
To evaluate a string as a mathematical expression in JavaScript, we can use the mathjs
library.