Revise suffixes and make them SI compliant

This commit is contained in:
Brett Gilio 2022-12-22 23:12:24 +00:00
parent 523834c403
commit bb11548b59
2 changed files with 11 additions and 12 deletions

View file

@ -1,12 +1,11 @@
export default (count: number) => {
const suffixes = [
{divisor: 1, suffix: ""},
{divisor: 1000, suffix: "k"},
{divisor: 1000000, suffix: "m"},
];
if (count < 1000) {
return count.toString();
}
const {divisor, suffix} =
suffixes[Math.min(suffixes.length - 1, Math.floor(Math.log10(count) / 3))];
return String(Math.ceil((count / divisor) * 10) / 10).concat(suffix);
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

@ -10,9 +10,9 @@ describe("roundBadgeNumber helper", 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 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 () {