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;

                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

5 Years
Discussion Span
Last Post by emreozpalamutcu

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.


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

Edited by emreozpalamutcu: n/a


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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.