public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter { public object GetFormat(Type formatType) { return (formatType == typeof(ICustomFormatter)) ? this : null; } public string Format(string format, object arg, IFormatProvider formatProvider) { var prefixes = "KMGTPEZY"; double input = Convert.ToDouble(arg); var imax = prefixes.Length - 1; var prefix = string.Empty; for (var i = 0; i <= imax; i++) { if (input < 1024) break; input /= 1024.0; prefix = prefixes[i].ToString(); } var result = string.Format("{0:" + format + "} {1}B", input, prefix); return result; } }
[TestClass] public class FileSizeFormatProviderTests { [TestMethod] public void TestFileSizeFormatProvider() { long fileSize = 1453178961; // 1,453,178,961 string s = string.Empty; var fp = new FileSizeFormatProvider(); s = string.Format(fp, "{0:0.000}", 1453178961); Assert.AreEqual("1.353 GB", s); s = string.Format(fp, "{0:0.000}", 1453164278961); Assert.AreEqual("1.322 TB", s); s = string.Format(fp, "{0:0.000}", 531453164278961); //531,453,164,278,961 Assert.AreEqual("483.354 TB", s); s = string.Format(fp, "{0:0.000}", 6531453996164278); //6,531,453,996,164,278 Assert.AreEqual("5.801 PB", s); s = string.Format(fp, "{0:0.000}", 6531453996164278961); //6,531,453,996,164,278,961 Assert.AreEqual("5.665 EB", s); } }