简体   繁体   English

具有十进制格式的C#string.format。

[英]C# string.format with decimal format.

DriveInfo[] drives = DriveInfo.GetDrives();
for (int i = 0; i < drives.Length; i++)
{
    if (drives[i].IsReady)
    {
        Console.WriteLine("Drive {0} - Has free space of {1} GB",drives[i].ToString(),(drives[i].TotalFreeSpace/1024/1024/1024).ToString("N2"));
    }
}

Output: 输出:

Drive C:\ - Has free space of 70,00 GB
Drive D:\ - Has free space of 31,00 GB
Drive E:\ - Has free space of 7,00 GB
Drive F:\ - Has free space of 137,00 GB

All end up with ,00 but I need to show real size. 全部以,00结尾,但我需要显示实际大小。 So which format is suitable? 那么哪种格式合适呢?

The format string doesn't have anything to do with it. 格式字符串与它无关。 Your integer operations are discarding any remainder. 您的整数运算将舍弃任何余数。

3920139012 / 1024 / 1024  / 1024 // 3

Specify decimals using the m suffix like so: 使用m后缀指定小数,如下所示:

3920139012 / 1024m / 1024m / 1024m // 3.6509139575064182281494140625

Alternatively: 或者:

3920139012 / Math.Pow(1024, 3) // 3.65091395750642

This might be a little more clear: 这可能更清楚一些:

var gb = Math.Pow(1024, 3);
foreach(var drive in DriveInfo.GetDrives())
{   
    if(drive.IsReady)
    {
        Console.WriteLine("Drive {0} - Has free space of {1:n2} GB",
            drive.Name,
            drive.TotalFreeSpace / gb);
    }
}

Becasue you are doing integer division which truncates decimal remainders. 因为您要进行整数除法 ,所以会舍去小数点后的位数。 Use floating-point division instead: 改用浮点除法:

drives[i].TotalFreeSpace/1024.0/1024.0/1024.0

or 要么

drives[i].TotalFreeSpace / (1024.0 * 1024.0 * 1024.0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM