问题描述
如何将数字格式化为固定的小数位数(保持尾随零),其中位数由变量指定?
How can I format a number to a fixed number of decimal places (keep trailing zeroes) where the number of places is specified by a variable?
例如
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 将不起作用(当然我不应该生成格式字符串):
Note that since I want to control the number of places programatically, this string.Format won't work (surely I ought not generate the format string):
Console.WriteLine(
string.Format("{0:0.000}", 1.2M)); // 1.200 (good)
我是否应该只包含 Microsoft.VisualBasic 并使用 格式编号?
Should I just include Microsoft.VisualBasic and use FormatNumber?
希望我在这里遗漏了一些明显的东西.
I'm hopefully missing something obvious here.
推荐答案
试试
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
了解更多信息.如果您发现附加的内容有点骇人听闻,请尝试:
for more information. If you find the appending a little hacky try:
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;
这篇关于如何在 c# 中将 Decimal 格式化为程序控制的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!