Skip to content

Instantly share code, notes, and snippets.

@msteini82
Forked from JonCatmull/file-size.pipe.ts
Last active February 25, 2020 11:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msteini82/6b77f92feda1f6f8286bc1bc7e6fd21b to your computer and use it in GitHub Desktop.
Save msteini82/6b77f92feda1f6f8286bc1bc7e6fd21b to your computer and use it in GitHub Desktop.
Angular2 + TypeScript file size Pipe/Filter. Convert bytes into largest possible unit. e.g. 1024 => 1 KB - Using standard decimal pipe to convert number to local format.
import { Pipe, PipeTransform, LOCALE_ID, Inject } from '@angular/core';
import {DecimalPipe} from '@angular/common';
/*
* 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 {
deciPipe: DecimalPipe;
private units = [
'Bytes',
'KB',
'MB',
'GB',
'TB',
'PB'
];
constructor(@Inject(LOCALE_ID) localeId) {
this.deciPipe = new DecimalPipe(localeId);
}
transform(bytes: number = 0, precision: number = 2 ): string {
if ( isNaN( parseFloat( String(bytes) )) || ! isFinite( bytes ) ) { return '?'; }
let unit = 0;
while ( bytes >= 1024 ) {
bytes /= 1024;
unit ++;
}
if (unit === 0) {
precision = 0;
}
return this.deciPipe.transform(bytes, '1.1-' + precision) + ' ' + this.units[ unit ];
}
}
@surerselcuk
Copy link

Error: if bytes < 1024 return none

Solution :
return bytes >= 1024 ? this.deciPipe.transform(bytes, '1.1-' + precision) + ' ' + this.units[ unit ] : bytes + ' ' + this.units[ unit ];

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