教程 decimaljs tutorial

安装方式

decimal.js 支持多种安装和引入方式,满足不同项目和环境的需求。

1. 使用 npm 或 yarn 安装

如果你的项目使用 Node.js 环境或现代前端构建工具(如 Vite、Webpack、Rollup 等),推荐通过包管理器安装:

bash
# 使用 npm
npm install decimal.js

# 或者使用 yarn
yarn add decimal.js

`

然后在代码中导入:

js
import Decimal from 'decimal.js';

const a = new Decimal(0.1);
const b = new Decimal(0.2);
console.log(a.plus(b).toString()); // "0.3"

2. 通过 CDN 引入

如果不使用构建工具,可以直接在 HTML 页面通过 CDN 引入:

html
<script src="https://cdn.jsdelivr.net/npm/[email protected]/decimal.min.js"></script>
<script>
  const a = new Decimal(0.1);
  const b = new Decimal(0.2);
  console.log(a.plus(b).toString()); // "0.3"
</script>