本文介绍了如何在C#中将小数格式化为以编程方式控制的小数位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

请注意,由于我想通过编程方式控制位置数,此字符串。格式将不起作用(肯定不会生成格式字符串):

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.

希望这对您有用。请参见

Hope this works for you. See

有关更多信息。如果您发现附加了一些小技巧,请尝试:

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#中将小数格式化为以编程方式控制的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 21:57