Skip to content

Instantly share code, notes, and snippets.

@maburdi94
Last active June 21, 2017 00:49
Show Gist options
  • Save maburdi94/e3311d755bee2b83c3a6768a5724f8b4 to your computer and use it in GitHub Desktop.
Save maburdi94/e3311d755bee2b83c3a6768a5724f8b4 to your computer and use it in GitHub Desktop.
Angular 2 data size formatter pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'dataSize'
})
export class DataSize implements PipeTransform {
private suffixes = ['KB', 'MB', 'GB', 'TB', 'EB', 'YB'];
// Specified input units (MB default (1000000))
transform(num: number, start = 1000000): any {
const idx0 = ~~(Math.log(start) / Math.log(1000));
const idx1 = ~~(Math.log(num) / Math.log(1000));
return `${(num / Math.pow(1000, idx1)).toFixed(1)} ${this.suffixes[idx0 + idx1 - 1]}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment