sharepulse/frontend/src/app/format-file-size-pipe.pipe.ts
2024-02-07 23:51:58 +01:00

20 lines
602 B
TypeScript

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'formatFileSizePipe',
standalone: true
})
export class FormatFileSizePipePipe implements PipeTransform {
transform(value: number, ...args: unknown[]): string {
if (value === null || value === 0) return '0 Bytes';
const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1);
const filesize = Number((value / Math.pow(1024, index)).toFixed(2));
return `${filesize.toLocaleString()} ${units[index]}`;
}
}