1,105,578 Community Members

How to format file sizes?

Member Avatar
emreozpalamutcu
Junior Poster in Training
78 posts since Dec 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Currently I have this code:

public static class SizeUnit
        {
            public static string FileSizeToString(long size)
            {
                double FileSize = size;

                string[] format = new string[] { "{0} bytes", "{0} KB", "{0} MB", "{0} GB", "{0} TB" };

                int i = 0;

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

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

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

Member Avatar
Momerath
Senior Poster
3,831 posts since Aug 2010
Reputation Points: 1,327 [?]
Q&As Helped to Solve: 664 [?]
Skill Endorsements: 19 [?]
Featured
 
0
 

What do you want to do if the number requires more digits, as in '1024 KB'?

Setting the number of digits after the decimal is easy, or the minimum number before the decimal. Setting a specific size doesn't always work right.

Member Avatar
emreozpalamutcu
Junior Poster in Training
78 posts since Dec 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I'm not sure but i can format it I just want to limit the number to 3 so that no matter what size it is it is going to max of 3 numbers from the start. I been searching for hours and it would be great if you could search too. Check my code most of the stuff is done just need to figure out how to do that limitation.

For example if the file size is 322.14 KB it should be 322 KB or if it is 320.50 MB it should be 320 MB but if it is 3.90 MB it shows it as 3.9 MB I want it to see the 0 at the end for MB and GB and TB only

Member Avatar
Momerath
Senior Poster
3,831 posts since Aug 2010
Reputation Points: 1,327 [?]
Q&As Helped to Solve: 664 [?]
Skill Endorsements: 19 [?]
Featured
 
1
 

You'll have to generate the result then parse the string into what you'd like to see. Start with using {0:0.000} as your format specifier, it will always put 3 numbers after the decimal (and only 3 numbers). From there you can remove characters to get it to the size you want.

Member Avatar
emreozpalamutcu
Junior Poster in Training
78 posts since Dec 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I'm not so great with c# can you edit my code?

Thank you

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: