This commit is contained in:
Brett Gilio 2024-04-25 09:19:26 +08:00 committed by GitHub
commit 0cf19ea886
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 11 additions and 2 deletions

View file

@ -3,5 +3,9 @@ export default (count: number) => {
return count.toString();
}
return (count / 1000).toFixed(2).slice(0, -1) + "k";
const suffixes = ["", "k", "M"];
const magnitudeIndex = Math.min(Math.floor(Math.log10(count) / 3), suffixes.length - 1);
const magnitude = 1000 ** magnitudeIndex;
const roundedCount = (count / magnitude).toFixed(1);
return roundedCount + suffixes[magnitudeIndex];
};

View file

@ -6,10 +6,15 @@ describe("roundBadgeNumber helper", function () {
expect(roundBadgeNumber(123)).to.equal("123");
});
it("should return numbers above 999 in thousands", function () {
it("should return numbers between 1000 and 999999 with a 'k' suffix", function () {
expect(roundBadgeNumber(1000)).to.be.equal("1.0k");
});
it("should return numbers above 999999 with a 'M' suffix", function () {
expect(roundBadgeNumber(1000000)).to.be.equal("1.0M");
expect(roundBadgeNumber(1234567)).to.be.equal("1.2M");
});
it("should round and not floor", function () {
expect(roundBadgeNumber(9999)).to.be.equal("10.0k");
});