2009-04-14 110 views
7

如何將一個數字格式化爲一個固定的小數位數(保持尾隨零),其中位數由變量指定?如何在c#中將Decimal格式化爲編程控制的小數位數?

例如

int x = 3; 
Console.WriteLine(Math.Round(1.2345M, x)); // 1.234 (good) 
Console.WriteLine(Math.Round(1M, x));  // 1 (would like 1.000) 
Console.WriteLine(Math.Round(1.2M, x)); // 1.2 (would like 1.200) 

注意,因爲我希望通過編程控制的名額,這樣的String.format是不行的(當然我不應該生成格式字符串):

Console.WriteLine(
    string.Format("{0:0.000}", 1.2M)); // 1.200 (good) 

我應該包括Microsoft.VisualBasic並使用FormatNumber

我希望在這裏明顯地丟失一些東西。

回答

12

嘗試

decimal x = 32.0040M; 
string value = x.ToString("N" + 3 /* decimal places */); // 32.004 
string value = x.ToString("N" + 2 /* decimal places */); // 32.00 
// etc. 

希望這對你的作品。見

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

以獲取更多信息。如果您發現該附加一個小哈克嘗試:

public static string ToRoundedString(this decimal d, int decimalPlaces) { 
    return d.ToString("N" + decimalPlaces); 
} 

然後,你可以調用

decimal x = 32.0123M; 
string value = x.ToRoundedString(3); // 32.012; 
+0

如何指定小數作爲變量的數目?我想我可以做(1.2M).ToString(「D」+ x),但這似乎有點hacky – 2009-04-14 20:31:28

+0

好吧,你可以隨時把它轉換爲擴展方法。 – 2009-04-14 20:34:21

1

像這樣的東西應該處理:

int x = 3; 
string format = "0:0."; 
foreach (var i=0; i<x; i++) 
    format += "0"; 
Console.WriteLine(string.Format("{" + format + "}", 1.2M)); 
4

試試這個動態創建自己的格式字符串,而無需使用多個步驟。

Console.WriteLine(string.Format(string.Format("{{0:0.{0}}}", new string('0', iPlaces)), dValue)) 

在步驟

//Set the value to be shown 
decimal dValue = 1.7733222345678M; 

//Create number of decimal places 
int iPlaces = 6; 

//Create a custom format using the correct number of decimal places 
string sFormat = string.Format("{{0:0.{0}}}", new string('0', iPlaces)); 

//Set the resultant string 
string sResult = string.Format(sFormat, dValue); 
0

方法,這樣做:

private static string FormatDecimal(int places, decimal target) 
     { 
      string format = "{0:0." + string.Empty.PadLeft(places, '0') + "}"; 
      return string.Format(format, target); 
     } 
相關問題