Android Code Snippet Format File Size

Hi to all.
I use below function to format file's size
Example if size of file is 12000 then result is 11.7 kb or 120000 is 12 Mb(if i write correct :) )

B4X:
Sub FormatSize(Size As Float) As String
   
    Dim unit() As String = Array As String(" Byte", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB")
   
    If (Size == 0) Then
        Return "N/A"
    Else
       
        Dim po,si As Double
        Dim i As Int
       
        i  = Floor(Logarithm(Size, 1024))
        po = Power(1024,i)
        si = Size / po
       
        Return si & unit(i)
       
    End If
   
End Sub
 

DonManfred

Expert
Licensed User
Longtime User

NJDude

Expert
Licensed User
Longtime User
A slightly better version:
B4X:
Sub FormatFileSize(Bytes As Float) As String
   
    Private Unit() As String = Array As String(" Byte", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB")
   
    If Bytes = 0 Then
					
       Return "0 Bytes"
    
    Else
       
       Private Po, Si As Double
       Private I As Int
       
       Bytes = Abs(Bytes)
							
       I = Floor(Logarithm(Bytes, 1024))
       Po = Power(1024, I)
       Si = Bytes / Po
       
       Return NumberFormat(Si, 1, 3) & Unit(I)
       
    End If
   
End Sub
 
Top