Willcode4cash

Convert file lengths to MB, GB, etc

Jun 23rd, 2017
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.66 KB | None | 0 0
  1. public static class Extensions
  2. {
  3.     public static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
  4.  
  5.     public static string AppendSizeSuffix(this Int64 value, int decimalPlaces = 0)
  6.     {
  7.         if (value < 0) { return "-" + AppendSizeSuffix(-value); }
  8.         if (value == 0) { return "0.0 bytes"; }
  9.  
  10.         int mag = (int)Math.Log(value, 1024);
  11.         decimal adjustedSize = (decimal)value / (1L << (mag * 10));
  12.         if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
  13.         {
  14.             mag += 1;
  15.             adjustedSize /= 1024;
  16.         }
  17.  
  18.         var rounded = string.Format("{0:n" + decimalPlaces + "}", adjustedSize);
  19.         return $"{rounded} {SizeSuffixes[mag]}";
  20.     }
  21. }
Advertisement
Add Comment
Please, Sign In to add comment