From ceadcd464e9a4f2ef99344a27ac5fb91b9c33f38 Mon Sep 17 00:00:00 2001 From: Dustin Brett Date: Fri, 30 Jun 2023 23:40:31 -0700 Subject: [PATCH] Adjust file size display --- __tests__/utils/functions.spec.tsx | 1 + utils/functions.ts | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/__tests__/utils/functions.spec.tsx b/__tests__/utils/functions.spec.tsx index 1ead3531..3ad3722d 100644 --- a/__tests__/utils/functions.spec.tsx +++ b/__tests__/utils/functions.spec.tsx @@ -14,6 +14,7 @@ describe("gets formatted size", () => { [1048081, "0.99 MB"], [9968640, "9.50 MB"], [16777216, "16.0 MB"], + [45266957, "43.1 MB"], ]; test.each(formattedSizeCases)("given %p render %p", (size, result) => diff --git a/utils/functions.ts b/utils/functions.ts index 82b7f744..243ff83e 100644 --- a/utils/functions.ts +++ b/utils/functions.ts @@ -493,12 +493,22 @@ const bytesInMB = 1022976; // 1024 * 999 const bytesInGB = 1047527424; // 1024 * 1024 * 999 const bytesInTB = 1072668082176; // 1024 * 1024 * 1024 * 999 -const formatNumber = (number: number): string => - new Intl.NumberFormat("en-US", { - maximumSignificantDigits: number < 1 ? 2 : 3, +const formatNumber = (number: number): string => { + const formattedNumber = new Intl.NumberFormat("en-US", { + maximumSignificantDigits: number < 1 ? 2 : 4, minimumSignificantDigits: number < 1 ? 2 : 3, }).format(Number(number.toFixed(4).slice(0, -2))); + const [integer, decimal] = formattedNumber.split("."); + + if (integer.length === 3) return integer; + if (integer.length === 2 && decimal.length === 2) { + return `${integer}.${decimal[0]}`; + } + + return formattedNumber; +}; + export const getFormattedSize = (size = 0): string => { if (size === 1) return "1 byte"; if (size < bytesInKB) return `${size} bytes`;