https://github.com/craftsys/eval-num-expr
Evaluate Numerical Expressions in Javascript ("25+3*22")
https://github.com/craftsys/eval-num-expr
Last synced: over 1 year ago
JSON representation
Evaluate Numerical Expressions in Javascript ("25+3*22")
- Host: GitHub
- URL: https://github.com/craftsys/eval-num-expr
- Owner: craftsys
- Created: 2021-04-16T15:48:58.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2021-05-25T11:59:34.000Z (about 5 years ago)
- Last Synced: 2024-08-10T11:29:21.392Z (almost 2 years ago)
- Language: TypeScript
- Homepage: https://craftsys.github.io/eval-num-expr/
- Size: 784 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Evaluate Numerical Expressions
## Installation
```
npm install --save eval-num-expr
```
## Usage
```js
import evalExpr from "eval-num-expr";
const value = evalExpr("100 + 3 * 55 + 73 - 73 * 18%");
// value = 324.86
// With Invalid Expressions handling
try {
const value = evalExpr("100 + (3 * 55");
} catch (e) {
// Will throw an exception for invalid expressions
console.error(e.message);
}
```
You can use basic operations (e.g. +, -, \*, /, %, ^ etc.) in you expressions.
### Examples
- 175 + 40 + 18% = 253.7
- 10 + (100 - 100 \* 18%) \* 5 + 40 / 20 = 422
> _NOTE_: Floating points must be handled carefully. Use `Number().toFixed()` to fix the digits after
> decimal point.
## Api
> This package supports TypeScript.
### evalExpr
This is the default and only export from this package.
```typescript
/**
* Evaluate numeric mathematical expression
* @param string expression - The expression to evaluate ("24 + 65 * 3 - 48")
* @return number - The evaluated value.
*
* @throws Will throw an error if the expression in invalid.
*
* NOTE: When passing floating points, please handle the digits after decimal point
* e.g. 2 - 1.1 leads to 0.8999999999999999 intead of .9
*/
evalExpr(expressions: string)
```