Skip to content

Commit 185e18f

Browse files
committed
added subscript and rounding to 3 decimals
1 parent 1391a31 commit 185e18f

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

packages/client/src/components/swaps-table.tsx

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import usePause from "@/hooks/use-pause";
1010
import { IToken } from "@/types";
1111
import {
1212
formatNumber,
13-
formatNumberSubscript,
13+
formatNumberSubscriptSmart,
1414
fromNow,
1515
LAMPORTS_PER_SOL,
1616
resizeImage,
@@ -162,8 +162,7 @@ export default function SwapsTable({ token }: { token: IToken }) {
162162
className="size-2.5 rounded-full"
163163
/>
164164
<span className="text-sm">
165-
{formatNumberSubscript(Number(solana), 2)}
166-
{/* {formatNumber(solana, true, true)} */}
165+
{formatNumberSubscriptSmart(Number(solana), 2)}
167166
</span>
168167
{usdValue ? (
169168
<span className="text-autofun-text-secondary text-xs">

packages/client/src/utils/index.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,43 @@ export const formatNumberSubscript = (
138138
}
139139
};
140140

141+
export const formatNumberSubscriptSmart = (
142+
num: number,
143+
decimals: number = 4,
144+
): string => {
145+
if (num === 0) return "0";
146+
let sign = "";
147+
if (num < 0) {
148+
sign = "-";
149+
num = Math.abs(num);
150+
}
151+
152+
if (num >= 1) {
153+
return sign + num.toFixed(decimals).toString();
154+
}
155+
156+
const expStr = num.toExponential();
157+
const [mantissa, exponentStr] = expStr.split("e");
158+
const exponent = parseInt(exponentStr, 10);
159+
let totalZeros = -exponent - 1;
160+
161+
if (totalZeros < 0) {
162+
totalZeros = 0;
163+
}
164+
165+
if (totalZeros >= decimals) {
166+
const mantissaDigits = mantissa.replace(".", "").slice(0, decimals + 1);
167+
return sign + "0." + toSubscript(totalZeros) + mantissaDigits;
168+
} else {
169+
const roundedMantissa =
170+
Math.ceil(Number(mantissa) * 10 ** decimals) / 10 ** decimals;
171+
const roundedString = roundedMantissa.toFixed(decimals);
172+
const mantissaDigits = roundedString.replace(".", "").slice(0, decimals);
173+
174+
return sign + "0." + "0".repeat(totalZeros) + mantissaDigits;
175+
}
176+
};
177+
141178
export const isFromDomain = (url: string, domain: string): boolean => {
142179
// if url does not have http or https, add it
143180
if (!url.startsWith("http") && !url.startsWith("https")) {

0 commit comments

Comments
 (0)