由于微信小程序不支持eval函数对数学表达式进行解析,所以需要另辟蹊径,而math.js数学库正好可以解决此类问题,并且功能强大。

Math.js是一个用于JavaScript和Node.js的扩展数学库 它提供了一个灵活的表达式解析器,支持符号计算,提供了大量的内置函数和常量,并提供了一个集成的解决方案来处理不同的数据类型,如数字 大数 复数 分数 单位和矩阵 强大和易于使用
(强烈建议在官网上学习)
官网地址:math.js | an extensive math library for JavaScript and Node.js
math.js特征
- 支持数字,大数,复数,分数,单位,字符串,数组和矩阵。
- 与JavaScript的内置Math库兼容。
- 包含一个灵活的表达式解析器。
- 进行符号计算。
- 带有大量内置函数和常量。
- 也可以用作命令行应用程序。
- 在任何JavaScript引擎上运行。
- 很容易扩展。
- 开源。
使用案例 :
// functions and constants
math.round(math.e, 3) // 2.718
math.atan2(3, -3) / math.pi // 0.75
math.log(10000, 10) // 4
math.sqrt(-4) // 2i
math.derivative('x^2 + x', 'x') // 2*x+1
math.pow([[-1, 2], [3, 1]], 2)
// [[7, 0], [0, 7]]
// expressions
math.evaluate('1.2 * (2 + 4.5)') // 7.8
math.evaluate('12.7 cm to inch') // 5 inch
math.evaluate('sin(45 deg) ^ 2') // 0.5
math.evaluate('9 / 3 + 2i') // 3 + 2i
math.evaluate('det([-1, 2; 3, 1])') // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done() // 14
以上案例仅仅是math.js的一小部分功能,它的强大超乎想象。
我用math.js为内核制作的微信小程序超级计算器:

这个计算器展示了math.js的部分功能,通过这个计算器,可以直观地了解这个数学库的强大功能。
如何使用?
-
方法一:
使用npm安装:
npm install mathjs
对微信小程序npm不熟悉的同学可以先查看微信官方文档:
npm 支持 | 微信开放文档
方法二:
直接下载到本地:
Download
Math.js can be downloaded or linked from various content delivery networks:
CDN | Url |
---|---|
unpkg | UNPKG - mathjs |
cdnjs | mathjs - Libraries - cdnjs - The #1 free and open source CDN built to make life easier for developers |
jsDelivr | mathjs CDN by jsDelivr - A CDN for npm and GitHub |
Here some direct download links from unpkg:
Development (version 7.0.0) | 1820 kB, 未压缩版 |
Production (version 7.0.0) | 551 kB, 压缩版(建议下载这个) |
推荐下载地址:https://cdnjs.cloudflare.com/ajax/libs/mathjs/7.0.0/math.min.js
点击下载链接之后,可看到如下页面,右键将网页另存为math.min.js,然后再将这个js文件导入到微信小程序工作目录下
然后再引入所需的math.min.js文件,即可使用这个强大的数学库:
const math = require('../utils/math.min.js');
