From 2fe36037371fc723d4d7219e884b8fb77298a8ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 26 Nov 2019 13:39:45 +0100 Subject: [PATCH] utils: Add an utility function to format bytes. --- src/utils/FormattingUtils.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/utils/FormattingUtils.js b/src/utils/FormattingUtils.js index 1fd7d00feb..9016d62cfb 100644 --- a/src/utils/FormattingUtils.js +++ b/src/utils/FormattingUtils.js @@ -30,6 +30,22 @@ export function formatCount(count) { return (count / 1000000000).toFixed(1) + "B"; // 10B is enough for anyone, right? :S } +/** + * format a size in bytes into a human readable form + * e.g: 1024 -> 1.00 KB + */ +export function formatBytes(bytes, decimals = 2) { + if (bytes === 0) return '0 Bytes'; + + const k = 1024; + const dm = decimals < 0 ? 0 : decimals; + const sizes = ['Bytes', '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 a key into groups of 4 characters, for easier visual inspection *