diff --git a/src/script/lib/helper.ts b/src/script/lib/helper.ts index beb24bea..04dedd49 100644 --- a/src/script/lib/helper.ts +++ b/src/script/lib/helper.ts @@ -176,23 +176,21 @@ export function numberWithCommas(number: number | string): string { if (typeof number === 'string') number = parseInt(number); return number.toLocaleString(); } else { - number = number.toString(); + const numberStr = number.toString(); - // Get numbers before `.` (if present) - const decimalIndex = number.indexOf('.'); - let output = decimalIndex === -1 ? number : number.slice(0, decimalIndex); - - // Insert commas every 3 digits from the right - for (let i = output.length - 3; i > 0; i -= 3) { - output = output.slice(0, i) + ',' + output.slice(i); + // Use regex to match the sign, integer part, and decimal part + const match = numberStr.match(/^(-?)(\d+)\.?(\d*)$/); + if (!match) { + return numberStr; // Return as-is if it doesn't match expected format } - // Append fractional part - if (decimalIndex !== -1) { - output += number.slice(decimalIndex); - } + const [, sign, integerPart, decimalPart] = match; + + // Add commas to integer part + const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ','); - return output; + // Combine sign, formatted integer, and decimal part + return sign + formattedInteger + (decimalPart ? '.' + decimalPart : ''); } } diff --git a/test/spec/lib/helper.spec.ts b/test/spec/lib/helper.spec.ts index fe2dcf46..c201b0ca 100644 --- a/test/spec/lib/helper.spec.ts +++ b/test/spec/lib/helper.spec.ts @@ -385,12 +385,43 @@ describe('Helper', function () { expect(numberWithCommas(123)).to.eql('123'); expect(numberWithCommas(1234)).to.eql('1,234'); expect(numberWithCommas(1234567890)).to.eql('1,234,567,890'); + expect(numberWithCommas(0)).to.eql('0'); + expect(numberWithCommas(-1234)).to.eql('-1,234'); }); it('Works with number string', function () { expect(numberWithCommas('123')).to.eql('123'); expect(numberWithCommas('1234')).to.eql('1,234'); expect(numberWithCommas('1234567890')).to.eql('1,234,567,890'); + expect(numberWithCommas('0')).to.eql('0'); + expect(numberWithCommas('-1234')).to.eql('-1,234'); + }); + + describe('Fallback logic when Intl is not available', function () { + let originalIntl: any; + + beforeEach(function () { + // Save original Intl + originalIntl = (global as any).Intl; + }); + + afterEach(function () { + // Restore original Intl + (global as any).Intl = originalIntl; + }); + + it('should use fallback logic when Intl is not available', function () { + // Remove Intl + delete (global as any).Intl; + + expect(numberWithCommas(123)).to.eql('123'); + expect(numberWithCommas(1234)).to.eql('1,234'); + expect(numberWithCommas(1234567890)).to.eql('1,234,567,890'); + expect(numberWithCommas(0)).to.eql('0'); + expect(numberWithCommas(-1234)).to.eql('-1,234'); + expect(numberWithCommas(1234.56)).to.eql('1,234.56'); + expect(numberWithCommas(-1234.56)).to.eql('-1,234.56'); + }); }); });