? ? ERC20的Token精度欄位為decimals,取值范圍為1~18,decimals默認為18,不同的Token,其decimals也是不同的,具體要根據Token合約代碼里的deicmals來進行判斷,在ethers.js里有個非常好的的庫utils,使用utils.formatUnits()、utils.parseUnits()可以非常方便的進行精度換算,
1 ETH --> WEI
- 若decimals=18,則
? ? y = utils.parseUnits(x,18) - 若decimals=6,則
? ? y = utils.parseUnits(x,6)
2 WEI --> ETH
-
若decimals=18,則
? ? y = utils.formatUnits(x,18) -
若decimals=6,則
? ? y = utils.formatUnits(x,6)
案例代碼
? ? //change.js
const { utils, BigNumber } = require("ethers")
function eth2Wei(x,decimals) {
return utils.parseUnits(x,decimals).toString()
}
function wei2Eth(x,decimals) {
return utils.formatUnits(x,decimals).toString()
}
async function doMain() {
//1) 已知 100 ethers X (100枚X), decimals = 18
// 求它可以轉化為多少wei?
let x1 = "100"
let decimals1 = 18
let y1 = eth2Wei(x1,decimals1)
console.log("wei: y1=",y1)
//2) 已知 100 ethers X (100枚X), decimals = 6
// 求它可以轉化為多少wei?
let x2 = "100"
let decimals2 = 6
let y2 = eth2Wei(x2,decimals2)
console.log("wei: y2=",y2)
//3) 在Solidity中,uint = wei
// 已知 500000000000000000000 uint X(用最小單位表示),decimals = 18
// 求它可以轉化為多少ethers?
let x3 = BigNumber.from("500000000000000000000")
let decimals3 = 18
let y3 = wei2Eth(x3,decimals3)
console.log("ethers: y3=",y3)
//4) 在Solidity中,uint = wei
// 已知 500000000000000000000 uint X(用最小單位表示),decimals = 6
// 求它可以轉化為多少ethers?
let x4 = BigNumber.from("500000000000000000000")
let decimals4 = 6
let y4 = wei2Eth(x4,decimals4)
console.log("ethers: y4=",y4)
}
doMain()
? ? 效果如下:
附錄
? ? 在黑框框命令列里,輸入如下命令即可安裝ethers.js
npm init -y
npm install ethers
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/404203.html
標籤:區塊鏈
