Skip to content

Commit 4f3abc5

Browse files
committed
fix(web): use ethers commify
1 parent 792af5f commit 4f3abc5

File tree

1 file changed

+47
-11
lines changed

1 file changed

+47
-11
lines changed

web/src/utils/commify.ts

Lines changed: 47 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,52 @@
1-
export const commify = (value: number | bigint | string): string => {
2-
const [integerPart, decimalPart] = value.toString().split(".");
1+
export function commify(value: string | number): string {
2+
const comps = String(value).split(".");
33

4-
let formattedIntegerPart = "";
5-
let counter = 0;
4+
if (
5+
comps.length > 2 ||
6+
!comps[0].match(/^-?[0-9]*$/) ||
7+
(comps[1] && !comps[1].match(/^[0-9]*$/)) ||
8+
value === "." ||
9+
value === "-."
10+
) {
11+
return value.toString();
12+
}
13+
14+
// Make sure we have at least one whole digit (0 if none)
15+
let whole = comps[0];
16+
17+
let negative = "";
18+
if (whole.substring(0, 1) === "-") {
19+
negative = "-";
20+
whole = whole.substring(1);
21+
}
22+
23+
// Make sure we have at least 1 whole digit with no leading zeros
24+
while (whole.substring(0, 1) === "0") {
25+
whole = whole.substring(1);
26+
}
27+
if (whole === "") {
28+
whole = "0";
29+
}
30+
31+
let suffix = "";
32+
if (comps.length === 2) {
33+
suffix = "." + (comps[1] || "0");
34+
}
35+
while (suffix.length > 2 && suffix[suffix.length - 1] === "0") {
36+
suffix = suffix.substring(0, suffix.length - 1);
37+
}
638

7-
for (let i = integerPart.length - 1; i >= 0; i--) {
8-
counter++;
9-
formattedIntegerPart = integerPart[i] + formattedIntegerPart;
10-
if (counter % 3 === 0 && i !== 0) {
11-
formattedIntegerPart = "," + formattedIntegerPart;
39+
const formatted: string[] = [];
40+
while (whole.length) {
41+
if (whole.length <= 3) {
42+
formatted.unshift(whole);
43+
break;
44+
} else {
45+
const index = whole.length - 3;
46+
formatted.unshift(whole.substring(index));
47+
whole = whole.substring(0, index);
1248
}
1349
}
1450

15-
return decimalPart ? `${formattedIntegerPart}.${decimalPart}` : formattedIntegerPart;
16-
};
51+
return negative + formatted.join(",") + suffix;
52+
}

0 commit comments

Comments
 (0)