how can we convert this java to find from bytes - kb,mb,gb (if theres another way im ok with it)

Posted on 2004-11-19
Last Modified: 2010-05-18
can someone please tell me in how to convert bytes to kb,mb,gb from any bytes number

id like the format of

4 Bytes
4.6 KB
4.6 MB
4.6 GB

that type of output bare in mind it would only be one of them

below is the code i found for java if that helps any

aka Pern
public String getFileSize(long fsize){
     //Set things up
     DecimalFormat   df         = new DecimalFormat("0.00");
     String              sizeType   = new String();
     String          returnSize = new String();
     //Calculate file sizes
      long fsize_kb   = fsize / 1024;
     long fsize_mb   = fsize / 1024 / 1024;
     long fsize_gb   = fsize / 1024 / 1024 / 1024;
      //Pick the right size i.e KB, MB or GB
      if(fsize_kb < 1500 ){
          returnSize = df.format(fsize_kb);
          sizeType = "KB";
      if(fsize_mb >= 1 && fsize_mb < 1000){
            returnSize = df.format(fsize_mb);
          sizeType = "MB";
       if(fsize_gb >=1){
            returnSize = df.format(fsize_gb);
          sizeType = "GB";
        //Return the size of the file with the right units....
       return(returnSize + sizeType);
Question by:Johnny
    LVL 28

    Expert Comment

    Enum FormatMemorySizeUnits
    End Enum

    ' convert a number of bytes into Kbytes, Megabytes, or Gigabytes

    Function FormatMemorySize(ByVal value As Long, _
        ByVal unit As FormatMemorySizeUnits, Optional ByVal decimalDigits As _
        Integer = 2, Optional ByVal omitThousandSeps As Boolean = False) As String
        ' simple error checking
        If value < 0 Then Throw New ArgumentException("Value can't be negative")

        ' get the best unit, if required
        If unit = FormatMemorySizeUnits.BestGuess Then
            Select Case value
                Case Is < 1023
                    unit = FormatMemorySizeUnits.Bytes
                    decimalDigits = 0
                Case Is < 1024 * 1023
                    unit = FormatMemorySizeUnits.Kilobytes
                Case Is < 1048576 * 1023
                    unit = FormatMemorySizeUnits.Megabytes
                Case Else
                    unit = FormatMemorySizeUnits.Gigabytes
            End Select
        End If

        ' evaluate the decimal value
        Dim val As Decimal
        Dim suffix As String

        Select Case unit
            Case FormatMemorySizeUnits.Bytes
                val = value
            Case FormatMemorySizeUnits.Kilobytes
                val = value / 1024
                suffix = "K"
            Case FormatMemorySizeUnits.Megabytes
                val = value / 1048576
                suffix = "M"
            Case FormatMemorySizeUnits.Gigabytes
                val = value / 1073741824
                suffix = "G"
        End Select

        ' get the string representation
        Dim format As String
        If omitThousandSeps Then
            format = "F" & decimalDigits.ToString
            format = "N" & decimalDigits.ToString
        End If

        Return val.ToString(format) & suffix
    End Function


    Author Comment

    im getting output like N2 KB

    for a value of 3638

    shouldnt it be around 3.4k or someplace around there??
    really confused

    Author Comment

    i also noticed it rouinds off its not exact

    Author Comment

    11603 is converting to 2 KB as well it seams this dont work...

    it should at least be 11k

    go figure
    LVL 4

    Accepted Solution

    here is a conversion for that java code you gave, it seems to work well:

        Private Function getFileSize(ByVal fsize As Double) As String
            'Set things up
            Dim sizeType, returnSize As String
            'Calculate file sizes
            Dim fsize_kb, fsize_mb, fsize_gb As Double
            fsize_kb = fsize / 1024
            fsize_mb = fsize_kb / 1024
            fsize_gb = fsize_mb / 1024
            'Pick the right size i.e KB, MB or GB
            If fsize_kb < 1500 Then
                sizeType = "KB"
                returnSize = Format(fsize_kb, "0.00")
            ElseIf fsize_mb >= 1 And fsize_mb < 1000 Then
                sizeType = "MB"
                returnSize = Format(fsize_mb, "0.00")
            ElseIf fsize_gb >= 1 Then
                sizeType = "GB"
                returnSize = Format(fsize_gb, "0.00")
                sizeType = "KB"
                returnSize = Format(fsize_kb, "0.000")
            End If
            Return returnSize & sizeType
        End Function

    Author Comment

    THANK YOU srcalc

    works perfectly

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
    Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…
    This video discusses moving either the default database or any database to a new volume.

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now