【问题标题】:C# string.format with decimal format.C# string.format 具有十进制格式。
【发布时间】:2014-01-21 21:09:10
【问题描述】:
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 结尾,但我需要显示实际尺寸。那么哪种格式适合呢?

【问题讨论】:

    标签: c# decimal string.format


    【解决方案1】:

    格式字符串与它没有任何关系。您的整数运算正在丢弃任何余数。

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

    【讨论】:

      【解决方案2】:

      因为您正在执行 整数除法,它会截断小数余数。改为使用浮点除法:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多