Decimal.js的常用方法
时间: 2023-12-07 14:05:17 浏览: 274
以下是Decimal.js的常用方法:
1. 加法
```javascript
let a = new Decimal(0.1);
let b = new Decimal(0.2);
let c = a.plus(b);
console.log(c.toString()); // 输出:0.3
```
2. 减法
```javascript
let a = new Decimal(0.3);
let b = new Decimal(0.1);
let c = a.minus(b);
console.log(c.toString()); // 输出:0.2
```
3. 乘法
```javascript
let a = new Decimal(0.1);
let b = new Decimal(0.2);
let c = a.times(b);
console.log(c.toString()); // 输出:0.02
```
4. 除法
```javascript
let a = new Decimal(0.3);
let b = new Decimal(0.1);
let c = a.dividedBy(b);
console.log(c.toString()); // 输出:3
```
5. 取反
```javascript
let a = new Decimal(0.1);
let b = a.negated();
console.log(b.toString()); // 输出:-0.1
```
6. 取绝对值
```javascript
let a = new Decimal(-0.1);
let b = a.abs();
console.log(b.toString()); // 输出:0.1
```
7. 取余数
```javascript
let a = new Decimal(10);
let b = new Decimal(3);
let c = a.modulo(b);
console.log(c.toString()); // 输出:1
```
8. 幂运算
```javascript
let a = new Decimal(2);
let b = new Decimal(3);
let c = a.toPower(b);
console.log(c.toString()); // 输出:8
```
9. 转换成Number类型
```javascript
let a = new Decimal(0.1);
let b = a.toNumber();
console.log(b); // 输出:0.1
```
10. 转换成String类型
```javascript
let a = new Decimal(0.1);
let b = a.toString();
console.log(b); // 输出:0.1
```
阅读全文