本文介绍了C# 十进制格式查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化小数,以便它显示如下:

I am trying to format a decimal so that it will get displayed as so:

14.5 应该显示为14.50"14.50 应显示为14.50"14.05 应该显示为14.05"14.00 应该显示为14"

14.5 should get displayed as "14.50"14.50 should get displayed as "14.50"14.05 should get displayed as "14.05"14.00 should get displayed as "14"

是否可以使用单一字符串格式,即不使用条件格式?

Is the possible with a single String Format, i.e. not using conditional formatting?

我试过0.##"(不满足第一个例子)和0.00"(不满足最后一个例子).

I've tried "0.##" (doesn't satisfy the first example) and "0.00" (doesn't satisfy the last example).

谢谢.

推荐答案

是的.您可以使用G"格式说明符.有关示例,请参阅 String.Format 的文档.

Yes. You can use the "G" format specifier. For samples, see String.Format's documentation.

例如:

decimal value = 14.05m;
string result = String.Format("{0:G}", value); // "14.05"

value = 14m;
result = String.Format("{0:G}", value); // "14"

这篇关于C# 十进制格式查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:28