Converts a length value to a readable size. - CSharp System

CSharp examples for System:Math Number

Description

Converts a length value to a readable size.

Demo Code


using System;/*from   w w  w  . j ava 2s .c om*/

public class Main{
        /// <summary>
        /// Converts a length value to a readable size.
        /// </summary>
        /// <param name="byteCount">The length of the file.</param>
        /// <returns>A string representation of a file size.</returns>
        public static string BytesToString(long byteCount)
        {
            string[] suf = { " B", " KB", " MB", " GB" }; //I hope no one make a gif with TB's of size. haha - Nicke

            if (byteCount == 0)
                return "0" + suf[0];

            var bytes = Math.Abs(byteCount);
            var place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            var num = Math.Round(bytes / Math.Pow(1024, place), 1);

            return (Math.Sign(byteCount) * num) + suf[place];
        }
}

Related Tutorials