Skip to content

Instantly share code, notes, and snippets.

@ryangoree
Last active March 13, 2023 20:00
Show Gist options
  • Save ryangoree/2fbc07b6093f0282c9bb29847efccbb3 to your computer and use it in GitHub Desktop.
Save ryangoree/2fbc07b6093f0282c9bb29847efccbb3 to your computer and use it in GitHub Desktop.
formatBytes - Format bytes as human-readable text.
/**
* Format bytes as human-readable text.
* @param {number} bytes Number of bytes.
* @param {number} decimalPlaces Number of decimal places to display.
* @param {number} baseQuantity Number of bytes in a kilobyte.
* @param {string[]} sizes The unites to use for each power of the baseQuantity.
* @return {string} Formatted byte size.
*/
export const formatBytes = (
bytes,
decimalPlaces = 1,
baseQuantity = 1024,
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB']
) => {
if (bytes === 0) return 'n/a'
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(baseQuantity)), 10)
if (i === 0) return `${bytes} ${sizes[i]}`
return `${(bytes / baseQuantity ** i).toFixed(decimalPlaces)} ${sizes[i]}`
}
/**
* Format bytes as human-readable text using SI (decimal) prefixes.
* @param {number} bytes Number of bytes.
* @param {number} decimalPlaces Number of decimal places to display.
* @return {string} Formatted byte size.
*/
export const formatBytesSI = (bytes, decimalPlaces) =>
formatBytes(bytes, decimalPlaces, 1000, [
'Bytes',
'kB',
'MB',
'GB',
'TB',
'PB',
])
/**
* Format bytes as human-readable text using IEC (binary) prefixes.
* @param {number} bytes Number of bytes.
* @param {number} decimalPlaces Number of decimal places to display.
* @return {string} Formatted byte size.
*/
export const formatBytesIEC = (bytes, decimalPlaces) =>
formatBytes(bytes, decimalPlaces, 1024, [
'Bytes',
'KiB',
'MiB',
'GiB',
'TiB',
'PiB',
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment