简体   繁体   English

.NET字符串格式化 - 小数点左边的#是什么意思?

[英].NET String formatting -What does the # mean to the left of the decimal point?

I have a need to format a numeric string to a maximum of 2 places either side of the decimal point, even if it means truncating or chopping off the leading digits (it's a long story, don't ask). 我需要将数字字符串格式化为小数点两边最多2个位置,即使这意味着截断或截断前导数字(这是一个很长的故事,不要问)。 On the MSDN it implies this can be done with the pound sign (#): 在MSDN上,它意味着可以使用井号(#)完成:

"The "#" custom format specifier serves as a digit-placeholder symbol. If the value that is being formatted has a digit in the position where the pound sign appears in the format string, that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string." “”#“自定义格式说明符用作数字占位符符号。如果格式化的值在格式字符串中出现井号的位置有一个数字,则该数字将复制到结果字符串。否则,没有任何东西存储在结果字符串中的那个位置。“

But in practice that only seems to work to the right of the decimal point. 但在实践中,似乎只能在小数点右侧工作。 If I do this: 如果我这样做:

String s = " Test - " + String.Format("format0 = {0:0.##}, format1 = {1:#.##}, format2 = {2:##.###}",321.2345, 321.2345, 321.2345);

I get this output for s: 我得到s的这个输出:

" Test - format0 = 321.23, format1 = 321.23, format2 = 321.235" “测试 - 格式0 = 321.23,格式1 = 321.23,格式2 = 321.235”

... note that "0.##" and "#.##" produced the same output. ...注意“0。##”和“#。##”产生相同的输出。 So what exactly does the "#" mean when it's to the left of the decimal point? 那么当它位于小数点左侧时,“#” 究竟是什么意思呢?

To paraphrase the documentation that you cited, the # makes the digit in that position optional. 为了解释您引用的文档#使该位置的数字可选。 If the number has a significant digit in that position, it will be printed; 如果该号码在该位置有一个重要数字,它将被打印; otherwise it will not. 否则它不会。

Take a look at this example: 看看这个例子:

String.Format("{0:0.##}, {0:#.##}", 0.5)

This will output 这将输出

0.5, .5

Or perhaps a more clear example: 或许是一个更明确的例子:

String.Format("{0:000.000}, {0:###.###}", 0.5)

This will output 这将输出

000.500, .5

0.## and #.## don't produce the same output. 0.###.##不产生相同的输出。

0m.ToString("0.##") // returns "0"

0m.ToString("#.##") // returns ""

0m.ToString("#.#0") // returns ".00"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM