Last active
June 21, 2017 00:49
-
-
Save maburdi94/e3311d755bee2b83c3a6768a5724f8b4 to your computer and use it in GitHub Desktop.
Angular 2 data size formatter pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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