Human Readable Size Formatting Extension

// December 14th, 2009 // Useful Code

This is a simple extension to turn unreadable sizes into something that makes more sense to the human eye. This will convert 1024 into 1KB or 1099511627776 into 1GB. This is by no means perfect, some additions could be made such as adding ,’s to separate the digits into proper grouping. Having said that most of the time grouping will be removed because numbers which should be grouped soon fall into the next sizing segment, meaning 1,000B becomes 1KB after only 24 more bytes.

//Code


        /// <summary>
        /// MAIN TO HUMAN READABLE FUNCTION TO CONVERT DOUBLES INTO XB, XKB, XMB, XGB
        /// </summary>
        /// <param name="x">INCOMING NUMBER TO MAKE READABLE</param>
        /// <returns>HUMAN READABLE SIZE FORMAT SUCH AS 1MB</returns>
        public static string ToHumanReadable(this double x)
        {
            //CONSTANTS FOR SIZING
            double KB = 1024;
            double MB = 1024 * KB;
            double GB = 1024 * MB;

            if (x < KB)
                return string.Format("{0}B", x);
            else if (x < MB)
            {
                return string.Format("{0:0.##}KB", x / KB);
            }
            else if (x < GB)
            {
                return string.Format("{0:0.##}MB", x / MB);
            }
            else if (x >= GB)
            {
                return string.Format("{0:0.##}GB", x / GB);
            }
            else
            {
                //HACK: GET RID OF COMPILER ERROR BECAUSE IT BELEIVES NOT ALL PATHS RETURN A VALUE
                return null;
            }
        }

        /// <summary>
        /// EXTENSION FOR LONG TO MAKE HUMAN READABLE
        /// </summary>
        /// <param name="x">INCOMING NUMBER TO MAKE READABLE</param>
        /// <returns>HUMAN READABLE SIZE FORMAT SUCH AS 1MB</returns>
        public static string ToHumanReadable(this long x)
        {
            return ToHumanReadable((double)x);
        }

        /// <summary>
        /// EXTENSION FOR INT TO MAKE HUMAN READABLE
        /// </summary>
        /// <param name="x">INCOMING NUMBER TO MAKE READABLE</param>
        /// <returns>HUMAN READABLE SIZE FORMAT SUCH AS 1MB</returns>
        public static string ToHumanReadable(this int x)
        {
            return ToHumanReadable((double)x);
        }

        /// <summary>
        /// EXTENSION FOR SINGLE TO MAKE HUMAN READABLE
        /// </summary>
        /// <param name="x">INCOMING NUMBER TO MAKE READABLE</param>
        /// <returns>HUMAN READABLE SIZE FORMAT SUCH AS 1MB</returns>
        public static string ToHumanReadable(this Single x)
        {
            return ToHumanReadable((double)x);
        }
Be Sociable, Share!
  • RSS
  • Twitter
  • Facebook
  • LinkedIn
  • DeviantArt