Skip to content

Instantly share code, notes, and snippets.

@tnqsoft
Created July 11, 2017 04:06
Show Gist options
  • Save tnqsoft/0d6b338e04790e94bfe1b02345a51b07 to your computer and use it in GitHub Desktop.
Save tnqsoft/0d6b338e04790e94bfe1b02345a51b07 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 | humanFileSize:precision
* Example:
* {{ 1024 | humanFileSize}}
* formats to: 1 KB
*/
@Pipe({
name: 'humanFileSize'
})
export class HumanFileSizePipe 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 = 0;
while ( bytes >= 1024 ) {
bytes /= 1024;
unit ++;
}
return bytes.toFixed(precision).toString().replace(/\./g, ',') + ' ' + this.units[ unit ];
}
}
@bracco23
Copy link

bracco23 commented Mar 2, 2018

Hello,

I was looking for something like this and I happefully found it here, thanks you very much!

I made a few changes that improve the output and the efficiency:

  • I used a combination of Math.log instead of the while to get the unit
  • Used toLocaleString instead of toString and dropped the replace to achieve a locale-compatible decimal separator
  • Reconverted the fixed-precision string back to a number to drop any 0 in the decimals.

Some other changes like in the name of the pipe or spaces

Here is the link of the updated gist, if you find them useful feel free to take the changes.

https://gist.github.com/bracco23/bfc7d6070b1aa094394f82c4c59db1e8

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