最近的工作需要使用JS进行数学计算并精确到N位小数,众所周知JS自身的数学计算因为采用了 IEEE 754 标准,导致涉及小数的计算时存在丢失精度的情况。
于是从网上找了mathjs,一个专业的JS数学计算库来解决该问题,这里记录下mathjs的用法
1 2 3 4 5 6
|
import { create, all } from 'mathjs'
Vue.prototype.$math = create(all, config)
|
1、直接使用方法
1 2 3 4 5
| this.$math.round(math.e, 3) this.$math.atan2(3, -3) / math.pi this.$math.log(10000, 10) this.$math.sqrt(-4) this.$math.derivative('x^2 + x', 'x')
|
2、使用表达式字符串
1 2 3 4 5
| this.$math.evaluate('1.2 * (2 + 4.5)') this.$math.evaluate('12.7 cm to inch') this.$math.evaluate('sin(45 deg) ^ 2') this.$math.evaluate('9 / 3 + 2i') this.$math.evaluate('det([-1, 2; 3, 1])')
|
3、链式操作
1 2 3 4
| this.$math.chain(3) .add(4) .multiply(2) .done()
|
常用方法:https://mathjs.org/docs/reference/functions.html
拓展阅读:JavaScript 浮点数之迷:0.1 + 0.2 为什么不等于 0.3?