From 018dc60f2071af520c9be40ffe556eb9127a2f59 Mon Sep 17 00:00:00 2001 From: "courtmanr@gmail.com" Date: Tue, 4 Mar 2025 10:03:39 +0000 Subject: [PATCH] Add utility functions for formatting bytes and percentages --- src/utils/format.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/utils/format.ts diff --git a/src/utils/format.ts b/src/utils/format.ts new file mode 100644 index 000000000..47c868716 --- /dev/null +++ b/src/utils/format.ts @@ -0,0 +1,36 @@ +/** + * Format bytes to human readable string + */ +export function formatBytes(bytes: number, decimals: number = 2): string { + if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B'; + + const k = 1024; + const dm = decimals; + const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + + const i = Math.floor(Math.log(bytes) / Math.log(k)); + + return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; +} + +/** + * Format percentage to string with % symbol + */ +export function formatPercentage(value: number): string { + if (value === undefined || value === null || isNaN(value)) return '0%'; + return `${Math.round(value)}%`; +} + +/** + * Convert bytes to megabytes + */ +export function bytesToMB(bytes: number): number { + return bytes / (1024 * 1024); +} + +/** + * Convert megabytes to bytes + */ +export function mbToBytes(mb: number): number { + return mb * 1024 * 1024; +} \ No newline at end of file