SizeToHuman$ - convert bytes to a human-readable size.

Started by Quin, February 23, 2025, 04:37:06 AM

Previous topic - Next topic

Quin

Why am I not surprised the Windows API provides a function for this too?
Thanks MrBcx, your wisdom knows no bounds ;D


Quin

I needed to convert a number (in bytes) to a human-readable value in my app, so I wrote this super basic function. It only supports up to terabytes at the moment, but it can be easily expanded.

Function SizeToHuman$(Size#)
    Local Res$
    Res$ = Str$(Size#, 1) + " B" ' Have as a default in case all else fails in the loop.
    If Size# < 1024.0 Then Return Res$
    Local Sizes$[4]
    Sizes$[0] = "KB"
    Sizes$[1] = "MB"
    Sizes$[2] ="GB"
    Sizes$[3] = "TB"
    For Int i = 0 To 3
        Size# /= 1024.0
        If Size# < 1024.0 Then
            Res$ = Using$("###.##", Size#) + " " + Sizes$[i]
            Exit For
        End If
    Next
    Return Res$
End Function

Having to write this gave me a whole new appreciation for the Using$ function, what a piece of wizardry!  :)