gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:38 31 4
gpt4 key购买 nike

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"));
}
}


输出:

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


全部以,00结尾,但我需要显示实际大小。那么哪种格式合适呢?

最佳答案

格式字符串与它无关。您的整数运算将舍弃任何余数。

3920139012 / 1024 / 1024  / 1024 // 3


使用 m后缀指定小数,如下所示:

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


或者:

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


这可能更清楚一些:

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);
}
}

关于c# - 具有十进制格式的C#string.format。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21269137/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com