如何在C#中将十进制数格式化为程序控制的小数位数?

8

如何将数字格式化为指定位数的小数(保留尾随零),其中位数由变量指定?

例如:

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吗?

我希望我没有漏掉什么显而易见的东西。

5个回答

14

尝试一下

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获取更多信息。如果您发现添加操作有点“hacky”,可以尝试:

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;

如何将小数位数指定为变量?我想我可以使用(1.2M).ToString("D"+x)但这似乎有点不专业。 - Michael Haren
你可以将它转换为扩展方法。 - Nick Berardi
2
请注意:"F"和"N"之间的区别:"N"会插入千位分隔符,而"F"则不会。 - Michael Haren

5

尝试使用以下方法动态创建自己的格式化字符串,而无需使用多个步骤。

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);

2

好的,那么生成格式字符串(“F”+x.ToString())就是诀窍了?我以为我只是缺少一个库。谢谢,Joel! - Michael Haren
但是...你在上面的答案评论中描述的不是同样的东西吗?你称之为“hacky”(即临时的,不规范的)? - Matt Grande
1
开玩笑地说,一次是黑客行为,两次就成了最佳实践。 - Joel Coehoorn

1

应该可以用类似这样的代码来处理它:

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

0

实现该功能的方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接