Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我如何使它将显示我的文件大小后只有两位数字的点(点)? 公共静态字符串FormatSize(双倍大小) { const long BytesInKilobytes=1024; const long BytesInMegabytes=BytesInKilobytes*1024; const long BytesInGigabytes=BytesInMegabytes*1024; const long BytesInTerabytes=BytesInGigabytes*1024; 元组单位; if(大小_C#_.net_Winforms - Fatal编程技术网

C# 我如何使它将显示我的文件大小后只有两位数字的点(点)? 公共静态字符串FormatSize(双倍大小) { const long BytesInKilobytes=1024; const long BytesInMegabytes=BytesInKilobytes*1024; const long BytesInGigabytes=BytesInMegabytes*1024; const long BytesInTerabytes=BytesInGigabytes*1024; 元组单位; if(大小

C# 我如何使它将显示我的文件大小后只有两位数字的点(点)? 公共静态字符串FormatSize(双倍大小) { const long BytesInKilobytes=1024; const long BytesInMegabytes=BytesInKilobytes*1024; const long BytesInGigabytes=BytesInMegabytes*1024; const long BytesInTerabytes=BytesInGigabytes*1024; 元组单位; if(大小,c#,.net,winforms,C#,.net,Winforms,在这个例子中,我看到了KB,我得到的是:116.1234567890 KB,我得到了点后的十个数字。 我怎样才能保证它只在点后给出两位数字呢?只要使用任何标准的.NET格式文本即可。要获取小数点后有两位数字的数值,可以使用{0:n2}: public static string FormatSize(double size) { const long BytesInKilobytes = 1024; const long Bytes

在这个例子中,我看到了KB,我得到的是:116.1234567890 KB,我得到了点后的十个数字。
我怎样才能保证它只在点后给出两位数字呢?

只要使用任何标准的.NET格式文本即可。要获取小数点后有两位数字的数值,可以使用
{0:n2}

public static string FormatSize(double size)
        {
            const long BytesInKilobytes = 1024;
            const long BytesInMegabytes = BytesInKilobytes * 1024;
            const long BytesInGigabytes = BytesInMegabytes * 1024;
            const long BytesInTerabytes = BytesInGigabytes * 1024;

            Tuple<double, string> unit;
            if (size < BytesInTerabytes)
                if (size < BytesInGigabytes)
                    if (size < BytesInMegabytes)
                        if (size < BytesInKilobytes)
                            unit = Tuple.Create(size, "B");
                        else
                            unit = Tuple.Create(size / BytesInKilobytes, "KB");
                    else
                        unit = Tuple.Create(size / BytesInMegabytes, "MB");
                else
                    unit = Tuple.Create(size / BytesInGigabytes, "GB");
            else
                unit = Tuple.Create(size, "TB");

            return String.Format("{0} {1}",unit.Item1,  unit.Item2);
        }
这应该给你:

 return String.Format("{0:n2} {1}", unit.Item1, unit.Item2);
有关更多信息,请参阅上的MSDN文档。

使用


您只需要使用formatstring,签出即可。
116.12 KB 
return String.Format("{0} {1}",Math.Round(unit.Item1, 2),  unit.Item2);