diff --git a/frontend/src/utils/__tests__/formatBytes.spec.ts b/frontend/src/utils/__tests__/formatBytes.spec.ts new file mode 100644 index 0000000000..0d22eede5e --- /dev/null +++ b/frontend/src/utils/__tests__/formatBytes.spec.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest' +import { formatBytes } from '../format' +import { formatByteRate } from '@/views/admin/ops/utils/opsFormatters' + +describe('fractional byte rates', () => { + it.each([[0.5, '0.5 Bytes'], [0.01, '0.01 Bytes'], [0, '0 Bytes'], [1024, '1 KB']])('formats %s bytes', (value, expected) => { + expect(formatBytes(value as number)).toBe(expected) + }) + + it('keeps the byte unit when an observation averages less than one byte per second', () => { + expect(formatByteRate(30, 1)).toBe('0.5 Bytes/s') + }) +}) diff --git a/frontend/src/utils/format.ts b/frontend/src/utils/format.ts index 87204ff158..980f014c7d 100644 --- a/frontend/src/utils/format.ts +++ b/frontend/src/utils/format.ts @@ -87,7 +87,7 @@ export function formatBytes(bytes: number, decimals: number = 2): string { const dm = decimals < 0 ? 0 : decimals const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] - const i = Math.floor(Math.log(bytes) / Math.log(k)) + const i = Math.max(0, Math.floor(Math.log(bytes) / Math.log(k))) return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i] }