Question How to format file sizes?

emreozpalamutcu

New member
Joined
Mar 7, 2012
Messages
2
Location
London, United Kingdom, United Kingdom
Programming Experience
Beginner
Currently I have this code:

C#:
 [LEFT]        public static class SizeUnit
        {
            public static string FileSizeToString(long size)
            {
                double FileSize = size;
                
                string[] format = new string[] { "{0} bytes", "{0:0.00} KB", "{0:0.00} MB", "{0:0.00} GB", "{0:0.00} TB" };


                int i = 0;


                while (i < format.Length && FileSize >= 1024)
                {
                    FileSize = (int)(100 * FileSize / 1024) / 100.0;
                    i++;
                }


                return string.Format(format[i], FileSize); 
            }
        }
[/LEFT]

The problem is I want it to display the size in this format with max 3 numbers!

3.90 MB | 322 KB | 4.33 KB | 300 Bytes | 0 Bytes | 3 MB | 12.5 MB | 300 MB | 32.5 KB | 700 Bytes
I use this code to display the result:

C#:
[COLOR=#660066][FONT=inherit]SizeUnit[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]FileSizeToString[/FONT][/COLOR][COLOR=#666600][FONT=inherit]([/FONT][/COLOR][COLOR=#000000][FONT=inherit]fileInfo[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Length[/FONT][/COLOR][COLOR=#666600][FONT=inherit])[/FONT][/COLOR]

Thanks...
 
Top Bottom