Reputation: 8281
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). On the MSDN it implies this can be done with the pound sign (#):
"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:
" Test - format0 = 321.23, format1 = 321.23, format2 = 321.235"
... note that "0.##" and "#.##" produced the same output. So what exactly does the "#" mean when it's to the left of the decimal point?
Upvotes: 4
Views: 196
Reputation: 28127
0.##
and #.##
don't produce the same output.
0m.ToString("0.##") // returns "0"
0m.ToString("#.##") // returns ""
0m.ToString("#.#0") // returns ".00"
Upvotes: 1
Reputation: 149040
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
Upvotes: 5