[Edit]
+
0
-
0

JavaScript - convert size in bytes to KB, MB, GB, TB, PB

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
const SHORT_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; const FULL_UNITS = ['bytes', 'kilobytes', 'megabytes', 'gigabytes', 'terabytes', 'petabytes']; const calculateParts = (size, units = SHORT_UNITS) => { const result = {}; for (const unit of units) { const total = Math.floor(size / 1024); const rest = size - 1024 * total; if (rest) { result[unit] = rest; } size = total; } return result; }; // --------------------------------------------------- // Practical example 1: // --------------------------------------------------- { const parts = calculateParts(31108834345654325); console.log( parts.PB + 'PB ' + parts.TB + 'TB ' + parts.GB + 'GB ' + parts.MB + 'MB ' + parts.KB + 'KB ' + parts.B + 'B' ); } // Output: // // 27PB 645TB 327GB 712MB 806KB 52B // --------------------------------------------------- // Practical example 2: // --------------------------------------------------- { const parts = calculateParts(31108834345654325, FULL_UNITS); console.log( parts.petabytes + ' petabytes, ' + parts.terabytes + ' terabytes, ' + parts.gigabytes + ' gigabytes, ' + parts.megabytes + ' megabytes, ' + parts.kilobytes + ' kilobytes, ' + parts.bytes + ' bytes' ); } // Output: // // 27 petabytes, 645 terabytes, 327 gigabytes, 712 megabytes, 806 kilobytes, 52 bytes // --------------------------------------------------- // See also: // --------------------------------------------------- // // 1. https://dirask.com/snippets/JavaScript-convert-size-in-bytes-to-KB-MB-GB-TB-PB-1XBMVp
Reset