如何在 c# 中将 Decimal 格式化为程序控制的小数位数?

33

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

问题描述

限时送ChatGPT账号..

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

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

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14