Advertisement
nbannister

Size suffix from bytes

Jun 3rd, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.89 KB | None | 0 0
  1. static readonly string [] SizeSuffixes =
  2.                    { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
  3.  
  4. static string SizeSuffix (ulong value, uint decimalPlaces = 1) {
  5.     if (value == 0) { return string.Format ("{0:n" + decimalPlaces + "} bytes", 0); }
  6.  
  7.     // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
  8.     int mag = (int) Mathf.Log (value, 1024);
  9.  
  10.     // 1L << (mag * 10) == 2 ^ (10 * mag)
  11.     // [i.e. the number of bytes in the unit corresponding to mag]
  12.     decimal adjustedSize = (decimal) value / (1L << (mag * 10));
  13.  
  14.     // make adjustment when the value is large enough that
  15.     // it would round up to 1000 or more
  16.     if (System.Math.Round (adjustedSize, (int) decimalPlaces) >= 1000) {
  17.         mag += 1;
  18.         adjustedSize /= 1024;
  19.     }
  20.  
  21.     return string.Format ("{0:n" + decimalPlaces + "} {1}",
  22.         adjustedSize,
  23.         SizeSuffixes [mag]);
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement