2014-06-21 27 views
2
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); 
     } 

在這種情況下,我看到知識產權,我得到的是:116.1234567890 KB我得到十點後的數字點。 我該如何讓它在點後僅給出兩位數?我如何使它在點(點)後僅顯示兩個數字的文件大小?

+0

你只需要使用formatString中,選中[這](http://msdn.microsoft.com/en-us/library/system.string.format(V = VS。 110).aspx)out。 – VahidNaderi

回答

5

只需使用任何標準的.NET格式文字即可。要獲得小數點後兩位的數值,可以使用{0:n2}

return String.Format("{0:n2} {1}", unit.Item1, unit.Item2); 

這應該給你:

116.12 KB 

欲瞭解更多信息,請參閱Standard Numeric Format Strings MSDN文檔。

2

使用Math.Round

return String.Format("{0} {1}",Math.Round(unit.Item1, 2), unit.Item2); 
相關問題