import { currentLocale } from './locale'; const SMALLEST_BYTE_UNIT = 'B'; const LARGER_BYTE_UNITS = [ 'KB', 'MB', 'GB' ] as const; const BYTES_PER_UNIT = 1024; const WHOLE_NUMBER_FROM = 100; export function formatNumber( count: number ): string { return count.toLocaleString( currentLocale() ); } export function formatPercent( percent: number ): string { return percent.toLocaleString( currentLocale(), { minimumFractionDigits: 1, maximumFractionDigits: 1, } ); } export function formatBytes( bytes: number ): string { let sizeInUnit = bytes; let unit: string = SMALLEST_BYTE_UNIT; for ( const largerUnit of LARGER_BYTE_UNITS ) { if ( sizeInUnit < BYTES_PER_UNIT ) { break; } sizeInUnit /= BYTES_PER_UNIT; unit = largerUnit; } const isWholeNumber = unit === SMALLEST_BYTE_UNIT || sizeInUnit >= WHOLE_NUMBER_FROM; const formattedSize = sizeInUnit.toLocaleString( currentLocale(), { maximumFractionDigits: isWholeNumber ? 0 : 1, } ); return `${ formattedSize } ${ unit }`; }