mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-28 20:04:26 +00:00
fix(webui): update file size formatting to SI decimal standard
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatSize } from './format'
|
||||
|
||||
describe('formatSize', () => {
|
||||
it('formats zero bytes', () => {
|
||||
expect(formatSize(0)).toBe('0 B')
|
||||
})
|
||||
|
||||
it('formats bytes below 1 KB', () => {
|
||||
expect(formatSize(500)).toBe('500 B')
|
||||
})
|
||||
|
||||
it('formats KB', () => {
|
||||
expect(formatSize(1000)).toBe('1 KB')
|
||||
expect(formatSize(1500)).toBe('1.5 KB')
|
||||
})
|
||||
|
||||
it('formats MB', () => {
|
||||
expect(formatSize(1000000)).toBe('1 MB')
|
||||
expect(formatSize(2500000)).toBe('2.5 MB')
|
||||
})
|
||||
|
||||
it('formats GB correctly using decimal standard', () => {
|
||||
expect(formatSize(4109222091)).toBe('4.11 GB')
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,20 @@
|
||||
export function formatSize(bytes: number): string {
|
||||
if (bytes === 0) return '0 B'
|
||||
const k = 1024
|
||||
if (!bytes || bytes <= 0) return '0 B'
|
||||
const k = 1000
|
||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
|
||||
let i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
if (i < 0) i = 0
|
||||
if (i >= sizes.length) i = sizes.length - 1
|
||||
|
||||
const val = bytes / Math.pow(k, i)
|
||||
if (i === 0) {
|
||||
return `${Math.round(val)} B`
|
||||
}
|
||||
|
||||
const formatted = parseFloat(val.toFixed(2))
|
||||
if (formatted >= 1000 && i < sizes.length - 1) {
|
||||
return parseFloat((bytes / Math.pow(k, i + 1)).toFixed(2)) + ' ' + sizes[i + 1]
|
||||
}
|
||||
|
||||
return `${formatted} ${sizes[i]}`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user