1 import { Pipe, PipeTransform } from '@angular/core'
3 // Thanks: https://github.com/danrevah/ngx-pipes/blob/master/src/ng-pipes/pipes/math/bytes.ts
5 @Pipe({ name: 'bytes' })
6 export class BytesPipe implements PipeTransform {
7 private dictionary: Array<{ max: number; type: string }> = [
8 { max: 1024, type: 'B' },
9 { max: 1048576, type: 'KB' },
10 { max: 1073741824, type: 'MB' },
11 { max: 1.0995116e12, type: 'GB' }
14 transform (value: number, precision?: number | undefined): string | number {
15 const format = this.dictionary.find(d => value < d.max) || this.dictionary[this.dictionary.length - 1]
16 const calc = value / (format.max / 1024)
18 const num = precision === undefined
20 : applyPrecision(calc, precision)
22 return `${num} ${format.type}`
26 function applyPrecision (num: number, precision: number) {
28 return Math.round(num)
31 const tho = 10 ** precision
33 return Math.round(num * tho) / tho