Skip to content

formatBytes() Helper Method

The formatBytes() Helper Method module provides a helper function that takes in a decimal number and an optional number of decimal places, and returns a formatted string of that number in the bytes, kilobytes, megabytes, etc. depending on the size of the input decimal number.

Import

To import the formatBytes() Helper Method:

javascript
import { formatBytes } from '@obewds/vueventus'

Arguments

Returns: String

ArgsTypeStatusDescription
bytesNumberRequiredA number of bytes
decimalsNumberRequiredA number of decimal places for the output number

Use Examples

javascript
console.log( formatBytes(0) )
// returns (string): '0 Bytes'

console.log( formatBytes(1000.12345, 5) )
// returns (string): '1000.12345 Bytes'

console.log( formatBytes(10000) )
// returns (string): '9.77 KB'

console.log( formatBytes(10000000) )
// returns (string): '9.54 MB'

console.log( formatBytes(10000000000) )
// returns (string): '9.31 GB'

console.log( formatBytes(10000000000000) )
// returns (string): '9.09 TB'

console.log( formatBytes(10000000000000000) )
// returns (string): '8.67 EB'

console.log( formatBytes(10000000000000000000000) )
// returns (string): '8.47 ZB'

console.log( formatBytes(10000000000000000000000000) )
// returns (string): '8.27 YB'

Module Code

ts
// ./src/helpers/formatBytes.ts

export default function (bytes: number, decimals = 2): string {

    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]

}

Released under the MIT License