-
Notifications
You must be signed in to change notification settings - Fork 499
/
Units.js
56 lines (49 loc) · 2.16 KB
/
Units.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { ethers } from "ethers";
// 1. BigNumber
console.group('\n1. BigNumber类');
const oneGwei = ethers.getBigInt("1000000000"); // 从十进制字符串生成
console.log(oneGwei)
console.log(ethers.getBigInt("0x3b9aca00")) // 从hex字符串生成
console.log(ethers.getBigInt(1000000000)) // 从数字生成
// 不能从js最大的安全整数之外的数字生成BigNumber,下面代码会报错
// ethers.getBigInt(Number.MAX_SAFE_INTEGER);
console.log("js中最大安全整数:", Number.MAX_SAFE_INTEGER)
// 运算
console.log("加法:", oneGwei + 1n)
console.log("减法:", oneGwei - 1n)
console.log("乘法:", oneGwei * 2n)
console.log("除法:", oneGwei / 2n)
// 比较
console.log("是否相等:", oneGwei == 1000000000n)
// 2. 格式化:小单位转大单位
// 例如将wei转换为ether:formatUnits(变量, 单位):单位填位数(数字)或指定的单位(字符串)
console.group('\n2. 格式化:小单位转大单位,formatUnits');
console.log(ethers.formatUnits(oneGwei, 0));
// '1000000000'
console.log(ethers.formatUnits(oneGwei, "gwei"));
// '1.0'
console.log(ethers.formatUnits(oneGwei, 9));
// '1.0'
console.log(ethers.formatUnits(oneGwei, "ether"));
// `0.000000001`
console.log(ethers.formatUnits(1000000000, "gwei"));
// '1.0'
console.log(ethers.formatEther(oneGwei));
// `0.000000001` 等同于formatUnits(value, "ether")
console.groupEnd();
// 3. 解析:大单位转小单位
// 例如将ether转换为wei:parseUnits(变量, 单位),parseUnits默认单位是 ether
console.group('\n3. 解析:大单位转小单位,parseUnits');
console.log(ethers.parseUnits("1.0").toString());
// { BigNumber: "1000000000000000000" }
console.log(ethers.parseUnits("1.0", "ether").toString());
// { BigNumber: "1000000000000000000" }
console.log(ethers.parseUnits("1.0", 18).toString());
// { BigNumber: "1000000000000000000" }
console.log(ethers.parseUnits("1.0", "gwei").toString());
// { BigNumber: "1000000000" }
console.log(ethers.parseUnits("1.0", 9).toString());
// { BigNumber: "1000000000" }
console.log(ethers.parseEther("1.0").toString());
// { BigNumber: "1000000000000000000" } 等同于parseUnits(value, "ether")
console.groupEnd();