-4

I have a table that stores the amount of RAM a server has in a biginit column with values such as 2470208.

But how I can apply a data annotation or other validations to show only 2 instead of s470208. ?

I mean to always divide by 1 million and get the number on the left side of the digit ?

4

2 回答 2

2

1)将此用于自动千单位:

string GetByteString(long n) {
    int k=0;
    string u=" kMGTEP";
    while(n>1024) {
        n>>=10;
        k++;
    }
    return n.ToString() + u[k];
}

称呼:

string s= GetByteString(1234567890123);
Debug.WriteLine(s);

2)但如果你只是总是想要 MB 只需移动 20:

long n = 123456789;
string MB = (n>>20).ToString();

但是如果n低于 1MB,这将显示 0。

原因:

1 kB = 2^10 = 1<<10 = 1024;  
1 MB = 2^20 = 1<<20 = 1024*1024 = 1048576;  
1 GB = 2^30 = 1<<30 = 1024*1024*1024 = 1073741824;
于 2013-08-16T18:48:35.943 回答
1

您标记了 C#,但提到了一个 bigint 列,因此不清楚您是在寻找数据库还是 C# 解决方案。以下 C# 方法将字节数作为整数并返回格式化字符串...

public string FormattedBytes(long bytes)
{
    string units = " kMGT";
    double logBase = Math.Log((double)bytes, 1024.0);
    double floorBase = Math.Floor(logBase);

    return String.Format("{0:N2}{1}b",
        Math.Pow(1024.0, logBase - floorBase),
        units.Substring((int)floorBase, 1));
}
于 2013-08-16T18:40:07.607 回答