本文介绍了确实.NET提供了一种简单的方法转换成字节,以KB,MB,GB等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只是想知道,.NET提供了一个干净的方式来做到这一点:
just wondering if .net provides a clean way to do this:
int64 x = 1000000;
string y = null;
if (x / 1024 == 0) {
y = x + " bytes";
}
else if (x / (1024 * 1024) == 0) {
y = string.Format("{0:n1} KB", x / 1024f);
}
等等...
etc...
推荐答案
下面是一个相当简洁的方式来做到这一点:
Here is a fairly concise way to do this:
static readonly string[] SizeSuffixes =
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value)
{
if (value < 0) { return "-" + SizeSuffix(-value); }
if (value == 0) { return "0.0 bytes"; }
int mag = (int)Math.Log(value, 1024);
decimal adjustedSize = (decimal)value / (1L << (mag * 10));
return string.Format("{0:n1} {1}", adjustedSize, SizeSuffixes[mag]);
}
和这里的原始实现我建议,这可能是稍微慢一些,但有点容易遵循:
And here's the original implementation I suggested, which may be marginally slower, but a bit easier to follow:
static readonly string[] SizeSuffixes =
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value)
{
if (value < 0) { return "-" + SizeSuffix(-value); }
int i = 0;
decimal dValue = (decimal)value;
while (Math.Round(dValue / 1024) >= 1)
{
dValue /= 1024;
i++;
}
return string.Format("{0:n1} {1}", dValue, SizeSuffixes[i]);
}
Console.WriteLine(SizeSuffix(100005000L));
这篇关于确实.NET提供了一种简单的方法转换成字节,以KB,MB,GB等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!