Skip to content

Commit e2f058e

Browse files
committed
⚡️ (dev): NumberWithCommas fallback negative and zero
1 parent 82753bd commit e2f058e

1 file changed

Lines changed: 11 additions & 13 deletions

File tree

src/script/lib/helper.ts

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -176,23 +176,21 @@ export function numberWithCommas(number: number | string): string {
176176
if (typeof number === 'string') number = parseInt(number);
177177
return number.toLocaleString();
178178
} else {
179-
number = number.toString();
179+
const numberStr = number.toString();
180180

181-
// Get numbers before `.` (if present)
182-
const decimalIndex = number.indexOf('.');
183-
let output = decimalIndex === -1 ? number : number.slice(0, decimalIndex);
184-
185-
// Insert commas every 3 digits from the right
186-
for (let i = output.length - 3; i > 0; i -= 3) {
187-
output = output.slice(0, i) + ',' + output.slice(i);
181+
// Use regex to match the sign, integer part, and decimal part
182+
const match = numberStr.match(/^(-?)(\d+)\.?(\d*)$/);
183+
if (!match) {
184+
return numberStr; // Return as-is if it doesn't match expected format
188185
}
189186

190-
// Append fractional part
191-
if (decimalIndex !== -1) {
192-
output += number.slice(decimalIndex);
193-
}
187+
const [, sign, integerPart, decimalPart] = match;
188+
189+
// Add commas to integer part
190+
const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
194191

195-
return output;
192+
// Combine sign, formatted integer, and decimal part
193+
return sign + formattedInteger + (decimalPart ? '.' + decimalPart : '');
196194
}
197195
}
198196

0 commit comments

Comments
 (0)