问题描述
如何将数字格式化为固定的小数位数(保持尾随零),其中位数由变量指定?
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 格式化为程序控制的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)