Disclaimer: I am not an expert in number parsing and, although many unit tests are in place for this library, I cannot confirm that it will work for all use cases, so do not use this library if reliability is important. I do not hold any liability if this code does not work as expected.
Not related to npm package of same name
A JavaScript library which parses an equation in string format to a number. It skips the traditional method of generating a syntax tree, instead evaluating the expression from the inside directly through a recursive method, resulting in code which often executes much more quickly than others (and sometimes orders of magnitude faster). This speed does not come at the cost of more advanced features; it supports implicit multiplication, multiple units of angles, and multiple custom variables.
- Evaluate mathematical expressions with the following operators:
^
,*
,/
,+
,-
- Evaluate mathematical expressions with the following operators containing a number inside the brackets, with trigonometric values represented in radians by default:
sqrt()
,sin()
,cos()
,tan()
,asin()
,acos()
,atan()
,abs()
- Evaluate mathematical expressions with brackets
- Evaluate mathematical expressions containing multi-digit positive and negative integers and floats
- Evaluate mathematical expressions involving the mathematical constants
e
andπ
(theenableConstants
parameter must be set to true for this to work) - Evaluate mathematical expressions involving variables in the Roman and Greek alphabets
- Evaluate mathematical expressions with trigonometric functions using either radians or degrees
(This is not an exhaustive list)
- Placing a number or variable immediately before a function (e.g.
8cos(0.5)
) - Modulus brackets (
|
) (please instead useabs()
)
The function accepts the following arguments in their respective order:
- equation (string): the equation to be parsed
- enableConstants (boolean, default is
true
): whether to enable the mathematical constantse
andπ
when parsing equation - variables (object, default is
null
): any custom variables to be used when parsing equation - angleMode (string, can be either
rad
ordeg
, default israd
): the mode to be used with the angles
{
"x": 0,
"y": -4.3
}
ParseMath('5 + 3 * 6 / 2') // 14
Number(ParseMath('3e').toFixed(3)) // 8.155
ParseMath('3x^2 - 5x + 3', true, {"x": 6}) // 81
Number(ParseMath('5*1-(sin(2)*tan(2))').toFixed(3)) // 6.987
Number(ParseMath('sin(arccos(0.5) + 1)', false, null, 'deg').toFixed(3)) // 0.875
Note that this library has the standard JavaScript floating point math issue where there are occasionally inaccurate results, such as 0.1 + 0.2 = 0.30000000000000004
. This can be resolved by the user by rounding the answer to an appropriate number of decimal places.
Again, this library has not been fully tested so may not work as expected with these abilities.