// file-size.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'fileSize', standalone: true }) export class FileSizePipe implements PipeTransform { transform(bytes: number): string { if (bytes < 1024) return `${bytes} B`; const units = ['KB', 'MB', 'GB', 'TB']; let size = bytes / 1024; let unitIndex = 0; while (size >= 1024 && unitIndex < units.length - 1) { size /= 1024; unitIndex++; } // Drop a trailing ".0" so 2 MB shows as "2 MB", not "2.0 MB". const rounded = Math.round(size * 10) / 10; return `${rounded} ${units[unitIndex]}`; } } // downloads.component.ts import { Component } from '@angular/core'; import { FileSizePipe } from './file-size.pipe'; @Component({ selector: 'app-downloads', standalone: true, imports: [FileSizePipe], template: `

{{ 512 | fileSize }}

{{ 1536 | fileSize }}

{{ 2097152 | fileSize }}

`, }) export class DownloadsComponent {} /* Notes: - The while loop steps up through the units (KB, MB, GB, TB), dividing by 1024 each time until the size is below 1024 or the largest unit is reached. - Rounding to one decimal and stripping a trailing .0 via Math.round keeps "2 MB" clean while still allowing "1.5 KB". */