Skip to content

Instantly share code, notes, and snippets.

@chrisengelsma
Created February 25, 2019 06:05
Show Gist options
  • Save chrisengelsma/cef1a89268a2be01ce7027100912891a to your computer and use it in GitHub Desktop.
Save chrisengelsma/cef1a89268a2be01ce7027100912891a to your computer and use it in GitHub Desktop.
Angular2+ Pipe to format bytes to human-legible units
import { Pipe } from '@angular/core';
/**
* Formats a byte value to a human-readable format.
*
* Example uses:
* -------------
* {{ value | formatBytes }} - use short units.
* {{ value | formatBytes: "long"}} - use long name units
*/
@Pipe({
name: 'formatBytes',
pure: false
})
export class FormatBytesPipe {
private _units: string[] = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'YB'];
private _unitsLong: string[] = [ 'Bytes', 'Kilobytes', 'Megabytes', 'Gigabytes', 'Terabytes', 'Pedabytes', 'Yottabytes'];
constructor() { }
transform(bytes: any, format: string): any {
if (!Number(bytes)) { return ''; }
let units: string[];
if (format === 'long') {
units = this._unitsLong;
} else {
units = this._units;
}
bytes = Math.max(bytes, 0);
let pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
pow = Math.min(pow, this._units.length - 1);
const value = bytes / (Math.pow(1000, pow));
return value + " " + units[pow];
}
}
@Argentum4k
Copy link

Argentum4k commented Apr 27, 2024

thanks 👍 But you should use pure: true and format = 'short' in params to use short form without second parameter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment