c#:如何在数字格式字符串中强制尾随零?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/787883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:11:16  来源:igfitidea点击:

c#: how to force trailing zero in numeric format string?

c#devexpress

提问by P a u l

I need to display float as

我需要将浮动显示为

1.00
1.50
1.55
1.60

The following is what I see using f2 format.

以下是我使用 f2 格式看到的内容。

1.
1.5
1.55
1.6

Is there a way to force the trailing 0 to appear?

有没有办强制尾随 0 出现?

(I'm using a DevExpress SpinEdit control and trying to set the display and edit format.)

(我正在使用 DevExpress SpinEdit 控件并尝试设置显示和编辑格式。)

采纳答案by LukeH

yourNumber.ToString("N2");

回答by Vadim

You can use syntax like this:

您可以使用这样的语:

String.Format("{0:0.00}", n)

回答by cookre

On those rare occasions I need to formatting, I go here:

在我需要格式化的极少数情况下,我去这里:

http://blog.stevex.net/index.php/string-formatting-in-csharp/

http://blog.stevex.net/index.php/string-formatting-in-csharp/

回答by Josh Kodroff

spinEdit.Properties.DisplayFormat.FormatType = FormatType.Numeric;
spinEdit.Properties.DisplayFormat.FormatString = "C2";

In the future, though, I would recommended searching Dev Express' knowledge baseor emailing support ([email protected]). They'll be able to answer your question in about a day.

不过,将来我建议搜索Dev Express 的知识库或发送电子邮件支持 ([email protected])。他们将能够在大约一天内回答您的问题。

回答by derekantrican

You can also do this with string interpolation (note that this is C# 6 and above):

您也可以使用字符串插值来执行此操作(请注意,这是 C# 6 及更高版本):

double num = 98765.4;
Console.WriteLine($"{num:0.00}"); //Replace "0.00" with "N2" if you want thousands separators