2009-04-14 119 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); 
     } 
相关问题