我有以下几点:
import { BigNumber } from "@ethersproject/bignumber";
import { parseUnits } from "@ethersproject/units";
const decimals = 18;
export const add = (a: string, b: string): string => {
const _a = parseUnits(a, decimals);
console.log(_a.toString(), a);
const _b = BigNumber.from(b);
const res = _a.add(_b).toString();
return res;
};
// a = 123456789123456789.123456789123456789
// b = 1
// _a.toString() = 123456789123456789123456789123456789
// res = 123456789123456789123456789123456790我是不是遗漏了一些显而易见的东西,为什么res不会被计算为"123456789123456790.123456789123456789"?
即使我没有传入decimals,结果仍然是一样的。(理想情况下,我不想指定实际的十进制值)
发布于 2021-05-30 18:33:28
BigNumber实际上是一个BigInteger (您不能在其中包含十进制值)。这是因为在以太区块链上,数字表示为256位整数。您还可以查看同一主题的my answer。
现在,使用小数可能会让人感到困惑,让我这样说:
// creating BigNumber instances
const a = ethers.BigNumber.from('1') // creates BigNumber of 1
const b = ethers.utils.parseUnits('1', 18) // Creates BigNumber of 1000000000000000000
const c = ethers.utils.parseEther('1') // same as above, by default 18 decimals
a.toString() // '1'
b.toString() // '1000000000000000000'
ethers.utils.formatEther(a) // '0.000000000000000001'
ethers.utils.formatEther(b) // '1.0'如果您主要处理带有小数的货币数字,那么您可以简单地使用parseEther和formatEther实用程序。
如果您没有使用货币,并且它仍然是一个BigNumber,那么您可以使用BigNumber.from()和value.toString()
https://stackoverflow.com/questions/67736793
复制相似问题