篇首语:本文由小编为大家整理,主要介绍了JavaScript的数学计算库:decimal.js相关的知识,希望对你有一定的参考价值。
文档:https://mikemcl.github.io/decimal.js/ github:https://github.com/MikeMcl/decimal.js npm地址:https://www.npmjs.com/package/decimal.js
对于小数点的处理可以获取0的个数,并乘以成整数进行运算。
1 整数和小数
2 简单的API,但功能齐全
3 复制了很多 javascript 的 Number.prototype 的方法和 Math 对象
4 也支持十六进制、二进制、八进制
5 比 Java 的 BigDecima l的 JavaScript 版本更快,更小,更容易使用
6 没有依赖
7 广泛的平台兼容性:仅使用 JavaScript 1.5(ECMAScript 3)功能
8 全面的文档和测试集
9 是 math.js 的底层实现
10 包含一个 TypeScript 声明文件:decimal.d.ts
该库是单个 JavaScript 文件 decimal.js 或 ES 模块 decimal.mjs。
浏览器
<script src='path/to/decimal.js'></script> <script type="module"> import Decimal from './path/to/decimal.mjs'; ...</script>
CDN
<script src="https://cdn.bootcdn.net/ajax/libs/decimal.js/10.3.1/decimal.js"></script>
Node.js
npm install decimal.jsconst Decimal = require('decimal.js'); import Decimal from 'decimal.js'; import Decimal from 'decimal.js';
<!doctype html><html lang="en"> <head> <meta charset="UTF-8"> <title>This is title</title> <script src="https://cdn.bootcdn.net/ajax/libs/decimal.js/10.3.1/decimal.js"></script><body><p class="container"> 这是p元素</p> <script> 0.1 + 0.2 // 0.30000000000000004 const x = new Decimal(0.1); const y = x.add(0.2); // 0.3 const z = Decimal(0.7).plus(x).plus(y).toFixed(2); // 1.10 console.log(y.toString()) console.log(z.toString())</script> </body></html>
结果
加 add 或者 plus
const a = 0.1 + 0.2 // 0.30000000000000004const x = new Decimal(0.1); // 0.1const y = x.add(0.2); // 0.3const z = Decimal(0.7).plus(x).plus(y).toFixed(2); // 1.10
减 sub 或 minus
const a = 0.3 - 0.1 // 0.19999999999999998const x = new Decimal(0.3); // 0.3const y = x.sub(0.1) // 0.2const z = Decimal(0.7).minus(x).minus(y).toFixed(2); // 0.20
乘 mul 或 times
const a = 0.6 * 3 // 1.7999999999999998const x = new Decimal(0.6) // 0.6const y = x.mul(3) // '1.8'const z = Decimal('7e+500').times(y) // '1.26e+501'
除 p 或 devidedBy
const x = new Decimal(5) // 5const y = new Decimal(3) // 3const z = x.p(y) // 1.6666666666666666667 Decimal.set( precision: 3, rounding: 2 )const z1 = x.p(y) // 1.67 Dec = Decimal.clone( precision: 4, rounding: 3 )const x1 = new Dec(5)const z2 = x1.pidedBy(y) // 1.66
以上是关于JavaScript的数学计算库:decimal.js的主要内容,如果未能解决你的问题,请参考以下文章