Skip to content

Commit 44d4401

Browse files
[BuyWidget] Handle very large numbers in FundWallet component
1 parent 85c4ef1 commit 44d4401

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

.changeset/legal-fans-enjoy.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"thirdweb": patch
3+
---
4+
5+
Handle very large numbers in BuyWidget

packages/thirdweb/src/react/web/ui/Bridge/FundWallet.tsx

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,9 @@ export function FundWallet({
112112
// Convert USD amount to token amount using token price
113113
const tokenAmount = usdAmount / uiOptions.destinationToken.priceUsd;
114114
// Format to reasonable decimal places (up to 6 decimals, remove trailing zeros)
115-
const formattedAmount = Number.parseFloat(
116-
tokenAmount.toFixed(6),
117-
).toString();
115+
const formattedAmount = toPlainString(
116+
Number.parseFloat(tokenAmount.toFixed(6)),
117+
);
118118
setAmount(formattedAmount);
119119
};
120120

@@ -341,3 +341,36 @@ export function FundWallet({
341341
</WithHeader>
342342
);
343343
}
344+
345+
function toPlainString(num: number) {
346+
const str = num.toString();
347+
348+
// If no exponential notation, return as-is
349+
if (str.indexOf("e") === -1) {
350+
return str;
351+
}
352+
353+
// Parse exponential notation
354+
const parts = str.split("e");
355+
const coefficient = parts[0];
356+
const exponent = parseInt(parts[1] ?? "0");
357+
358+
// Handle negative exponents (small numbers)
359+
if (exponent < 0) {
360+
const zeros = "0".repeat(Math.abs(exponent) - 1);
361+
const digits = coefficient?.replace(".", "") || "";
362+
return `0.${zeros}${digits}`;
363+
}
364+
365+
// Handle positive exponents (large numbers)
366+
const [integer, decimal = ""] = coefficient?.split(".") || [];
367+
const zerosNeeded = exponent - decimal.length;
368+
369+
if (zerosNeeded >= 0) {
370+
return `${integer}${decimal}${"0".repeat(zerosNeeded)}`;
371+
} else {
372+
const insertAt = (integer?.length ?? 0) + zerosNeeded;
373+
const result = integer + decimal;
374+
return `${result.slice(0, insertAt)}.${result.slice(insertAt)}`;
375+
}
376+
}

0 commit comments

Comments
 (0)