calculate-string
v2.0.2
Published
Parses a string containing mathematical operators to a number
Downloads
22,660
Readme
Table of Contents
Introduction
Why?
So you can parse a string without using unsafe evals nor have to spend a detour creating a parser.
Installation
With npm:
$ npm install calculate-string
With yarn:
$ yarn add calculate-string
Usage
Try me on RunKit
const calculateString = require('calculate-string')
calculateString('1,000 + 1,000') // String: '2000'
calculateString('(100 + 10) / 10') // String: '11'
BigInt(calculateString('2 ** 64')) // BigInt: 18,446,744,073,709,551,616
BigInt(calculateString('NaN')) // SyntaxError: Cannot convert NaN to a BigInt
Number(calculateString('1e+6 ^ -1e+6')) // Number: -Infinity
calculateString("this won't get parsed")) == 'NaN' // Boolean: true
calculateString('1,000,000 ^ 10') // String: '1e+60'
Number(calculateString('1,000,000 ^ 10')) // Number: 1e+60
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/calculate-string/index.min.js"></script>
</head>
<body>
<p id="result"></p>
<script>
document.getElementById("result").innerHTML = calculateString(
"100 + 100"
);
</script>
</body>
</html>