formatUnits fraction length #3657
Replies: 4 comments
-
I don't think I would make this change. The complexities around what is intended in rounding would mean the behaviour is not what many would expect, depending on the rounding strategy they expected. Also, formatting of significant digits is very case dependant. For example, some would want Which is why the output format is intended to be very predictable (i.e. always exactly one decimal point and at least one of each whole and fractional components), which make it easy to to reprocess as a string if desired. The string can always be split using Otherwise, the FixedNumber class enables simplifying converting a value by using any rounding strategy first to the desired resolution and then formatting to the target depth. Does that make sense? |
Beta Was this translation helpful? Give feedback.
-
it's an optional parameter. and in ethereum world, |
Beta Was this translation helpful? Give feedback.
-
I use this code: import { BigNumberish, ethers } from 'ethers';
export default function formatUnits(
value: BigNumberish,
decimals: string | BigNumberish = 0,
maxDecimalDigits?: number
) {
return ethers.FixedNumber.from(ethers.utils.formatUnits(value, decimals))
.round(maxDecimalDigits ?? ethers.BigNumber.from(decimals).toNumber())
.toString();
} formatUnits(ethers.BigNumber.from('3224686211026'), 8)
// '32246.86211026'
formatUnits(ethers.BigNumber.from('3224686211026'), 8, 2)
// '32246.86'
formatUnits(ethers.BigNumber.from('3224680211026'), 8, 2)
// '32246.8' |
Beta Was this translation helpful? Give feedback.
-
I likely won't make any formatting API changes, especially to v5, but the solution from @lomocc looks good. Moving this to Q&A Discussions, so it's easier for people to find in the future. ;) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Describe the Feature
current implementation is full length, but for most token 18 decimals is too long.
Code Example
Beta Was this translation helpful? Give feedback.
All reactions