Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Converting bytes to KB, MB, GB 1

Status
Not open for further replies.

robertfah

Programmer
Mar 20, 2006
380
US
I've got this function that converts bytes to a more readable format (ie. KB, MB, GB, etc):

Code:
    public string ConvertBytes(long lBytes)
    {
        string sSize = string.Empty;

        if (lBytes >= 1073741824)
            sSize = String.Format("{0:##.##}", lBytes / 1073741824) + " GB";
        else if (lBytes >= 1048576)
            sSize = String.Format("{0:D}", lBytes / 1048576) + " MB";
        else if (lBytes >= 1024)
            sSize = String.Format("{0:##.##}", lBytes / 1024) + " KB";
        else if (lBytes > 0 && lBytes < 1024)
            sSize = lBytes.ToString() + " bytes";

        return sSize;
    }

It works great with one exception, it rounds everything. For instance, if I have this stored in my DB '3556352' and once put through the above function, it spits out 3MB, when in reality, it's 3,473KB or 3.4MB. Is there anyway to get it to display 3.4MB instead of 3?

Thanks!
 
sSize = String.Format("{0:D}", lBytes / 1048576) + " MB";

isnt D a long date format?
shouldnt it be...

sSize = String.Format("{0:##.##}", lBytes / 1048576) + " MB";
 
I use to have the MB formatted like that (sSize = String.Format("{0:##.##}", lBytes / 1048576) + " MB") but it still rounds up. I was trying D from the page that jdemmi suggested but it's still rounding for some reason....
 
Its because of the C# formatting engine. it better handles the rounding when using a Double.

i got this working, stating 3 MB and 3.39 MB

Code:
long lng = 3556352;
//long lng = 3145728; // gives an even 3 to see what happens (3 MB results)
lblTestSringRounding.Text = String.Format("{0:##.##}", (Convert.ToDouble(lng) / 1048576)) + " MB";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top