Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Utility for formatting numbers into Bytes, KB,MB,GB, and TB
- /// </summary>
- public static class ByteFormatter
- {
- public const bool WITH_DIGITS_DEFAULT = true;
- public const long KB = 1024;
- public const long MB = KB * 1024;
- public const long GB = MB * 1024;
- public const long TB = GB * 1024;
- public const string BFormatPattern = "{0:N0} bytes";
- public const string KBFormatPattern = "{0:N0} KB";
- public const string MBFormatPattern = "{0:N0} MB";
- public const string GBFormatPattern = "{0:N0} GB";
- public const string TBFormatPattern = "{0:N0} TB";
- public const string KBFormatPattern_wDigits = "{0:N2} KB";
- public const string MBFormatPattern_wDigits = "{0:N2} MB";
- public const string GBFormatPattern_wDigits = "{0:N2} GB";
- public const string TBFormatPattern_wDigits = "{0:N2} TB";
- public static string ToFormat(double size)
- {
- return ToFormat(size,WITH_DIGITS_DEFAULT);
- }
- public static string ToFormat(double size,bool withDigits)
- {
- string kbfmt = KBFormatPattern;
- string mbfmt = MBFormatPattern;
- string gbfmt = GBFormatPattern;
- string tbfmt = TBFormatPattern;
- if(withDigits)
- {
- kbfmt = KBFormatPattern_wDigits;
- mbfmt = MBFormatPattern_wDigits;
- gbfmt = GBFormatPattern_wDigits;
- tbfmt = TBFormatPattern_wDigits;
- }
- if(size < KB)
- {
- return String.Format(BFormatPattern,size);
- }
- else if(size >= KB && size < MB)
- {
- return String.Format(kbfmt,size / 1024.0f);
- }
- else if(size >= MB && size < GB)
- {
- return String.Format(mbfmt,(size / 1024.0f) / 1024.0f);
- }
- else if(size >= GB && size < TB)
- {
- return String.Format(gbfmt,((size / 1024.0f) / 1024.0f) / 1024.0f);
- }
- else if(size >= TB)
- {
- return String.Format(tbfmt,(((size / 1024.0f) / 1024.0f) / 1024.0f) / 1024f);
- }
- else
- return String.Format(tbfmt,(((size / 1024.0f) / 1024.0f) / 1024.0f) / 1024f);
- }
- public static string ToString(long size,bool withDigits = WITH_DIGITS_DEFAULT)
- {
- return ToFormat(size,withDigits);
- }
- public static string FormatBytes(this short size,bool withDigits = WITH_DIGITS_DEFAULT)
- {
- return ToFormat(size,withDigits);
- }
- public static string FormatBytes(this int size,bool withDigits = WITH_DIGITS_DEFAULT)
- {
- return ToFormat(size,withDigits);
- }
- public static string FormatBytes(this long size,bool withDigits = WITH_DIGITS_DEFAULT)
- {
- return ToFormat(size,withDigits);
- }
- public static string FormatBytes(this decimal size,bool withDigits = WITH_DIGITS_DEFAULT)
- {
- return ToFormat((double)size,withDigits);
- }
- public static string FormatBytes(this double size,bool withDigits = WITH_DIGITS_DEFAULT)
- {
- return ToFormat(size,withDigits);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment