Skip to content

Commit

Permalink
libs: utils: Add function to convert number in bytes to human-readabl…
Browse files Browse the repository at this point in the history
…e string
  • Loading branch information
rafaellehmkuhl committed Feb 21, 2024
1 parent dd567cd commit d2cdafa
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/libs/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,15 @@ export const isValidNetworkAddress = (maybeAddress: string): boolean => {
}
return false
}

export const formatBytes = (bytes: number, decimals = 2): string => {
if (!bytes) return '0 Bytes'

const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']

const i = Math.floor(Math.log(bytes) / Math.log(k))

return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
}

0 comments on commit d2cdafa

Please sign in to comment.