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的个数,并乘以成整数进行运算。

decimal.js特性

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.js

const 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>
<div class="container">
    这是div元素
</div>
 
<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

扫描二维码关注公众号,回复: 14276842 查看本文章
const a = 0.1 + 0.2                        // 0.30000000000000004
const x = new Decimal(0.1);                // 0.1
const y = x.add(0.2);                      // 0.3
const z = Decimal(0.7).plus(x).plus(y).toFixed(2);  // 1.10

减 sub 或 minus

const a = 0.3 - 0.1                     // 0.19999999999999998
const x = new Decimal(0.3);             // 0.3
const y = x.sub(0.1)                    // 0.2
const z = Decimal(0.7).minus(x).minus(y).toFixed(2);  // 0.20

乘 mul 或 times

const a = 0.6 * 3                          // 1.7999999999999998
const x = new Decimal(0.6)                 // 0.6
const y = x.mul(3)                         // '1.8'
const z = Decimal('7e+500').times(y)       // '1.26e+501'

除 div 或 devidedBy

const x = new Decimal(5)         // 5
const y = new Decimal(3)         // 3
const z = x.div(y)               // 1.6666666666666666667
 
Decimal.set({
    
     precision: 3, rounding: 2 })
const z1 = x.div(y)              // 1.67
 
Dec = Decimal.clone({
    
     precision: 4, rounding: 3 })
const x1 = new Dec(5)
const z2 = x1.dividedBy(y)       // 1.66

猜你喜欢

转载自blog.csdn.net/weiguang102/article/details/125291586