Skip to content

Instantly share code, notes, and snippets.

@bracco23
Forked from tnqsoft/human-file-size.pipe.ts
Last active March 2, 2018 13:11
Show Gist options
  • Save bracco23/bfc7d6070b1aa094394f82c4c59db1e8 to your computer and use it in GitHub Desktop.
Save bracco23/bfc7d6070b1aa094394f82c4c59db1e8 to your computer and use it in GitHub Desktop.
Angular 4 Human file size in English
import { Pipe, PipeTransform } from '@angular/core';
/*
* Convert bytes into largest possible unit.
* Takes an precision argument that defaults to 2.
* Usage:
* bytes | fileSize:precision
* Example:
* {{ 1024 | fileSize}}
* formats to: 1 KB
*/
@Pipe({
name: 'fileSize'
})
export class FileSizePipe implements PipeTransform {
// In fact unit we should be get from Static Api, at the moment we set static
private units = ['B','kB','MB','GB','TB','PB','EB','ZB','YB'];
// In French
// private units = ['bit', 'kilo', 'Mo', 'Go', 'To', 'bps', 'dpi'];
public transform(bytes: number = 0, precision: number = 2 ) : string {
if ( isNaN( parseFloat( String(bytes) )) || ! isFinite( bytes ) ) {
return bytes.toString();
}
let unit = Math.floor(Math.log(bytes) / Math.log(1024));
let scaledValue = bytes / ( 1024 ** unit);
return (+scaledValue.toFixed(precision)).toLocaleString() + this.units[ unit ];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment