formatEther formatting options (namely max decimals) #955
Unanswered
SaulDope
asked this question in
Idea / Feature Request
Replies: 2 comments
-
For now, check out dnum's |
Beta Was this translation helpful? Give feedback.
0 replies
-
For anyone looking, I wrote a solution: export function customFormatEther(
wei: bigint,
maxDecimals: number = 18,
rounding: "floor" | "ceil" | "round" = "round",
) {
const power = 10n ** BigInt(18 - maxDecimals);
const remainder = wei % power;
const firstDecimal = remainder / 10n ** BigInt(18 - maxDecimals - 1);
let b = wei - remainder;
if (rounding === "ceil" || (rounding === "round" && firstDecimal >= 5)) {
b += power;
}
return formatEther(b);
} Usage: customFormatEther(weiAmount, 4) EDIT: simplified the method. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
When I'm doing math I want to keep the decimals of course, but when I want to display things to users I want to be able to truncate irrelevant decimals.
From an example on my site, I have a calculation that resulted in 39999999999999996 wei, or 0.039999999999999996 ether.
This is obviously ridiculous to show to users, realistically I would want to show something like 0.03999 or even 0.04. I decided to go with the following simple truncate logic, you could likely do better if you offered more intelligent rounding options like RoundBank, RoundDown etc.
Should be a decent option for a new contributor to implement, I would be down to do so
Beta Was this translation helpful? Give feedback.
All reactions