C# 格式字符串 "# ### ###.##"小于 1 时缺少零

标签 c# format

当使用格式字符串“# ### ###.##”时,显示的值是正确的。但是,当要显示像 0.12 这样的数字时,我只能看到 ,12 (由于国家/地区设置,逗号十进制字符被正确使用)。

(我尝试在格式化字符串的开头添加零,但这用零填充了无关紧要的位置。)

我应该如何修改格式字符串,以便 0.12 显示为 0,12...保留按 3 分组的大数字,并用空格分隔,例如 1 234 567,89

最佳答案

前导#占位符不会显示零,要获得最小零,您需要如下格式:

"# ### ##0.##"

文档中没有具体描述这样的示例,但这是相关引用:

The "0" custom specifier
The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string.

The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.

所以当使用 The "#" custom specifier 时我们只需在最左边位置放置一个0即可确定始终可见的数字的最小长度。

在您的情况下,小数点左侧至少需要 1 位数字,因此您将零放在小数点前面的数字中。

如果您想要相同的格式,并且小数点前的位数最少,那么您可以使用如下格式:

"# ### 0##.##"

然后 0.12 将被格式化为:

000.12

还需要注意的是,在当前格式中没有最小小数位数,因此值 0.1 将如下所示:

0.1

因此,如果您想始终显示 2 位小数,则最小格式如下所示:

"# ### ##0.#0"

使用此格式,0 值将呈现为:

0.00

It is worth noting that for a value of 0 and a format of "#.##"
no value will be rendered at all!
Because that format pattern does not specify that any zeros are required.

关于C# 格式字符串 "# ### ###.##"小于 1 时缺少零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77125649/

相关文章:

format - Opengl 是当今桌面上最好的纹理压缩格式

c - 使用 scanf() 分隔符未按预期工作

c# - Unity, C#, Dictionary, 计算一场比赛的球队得分

c# - Silverlight 5 和 dll

c# - Selenium:FindsBy 与集合

C# 二进制常量表示

使用 numeral.js 格式化大数字

c# - 新库中的异步与非异步方法

C# 方法解析,long 与 int

Android DatePickerDialog 标题问题