CShark
CShark

Reputation: 1622

In c#, is there any reason for having adjacent #'s on the left side of a decimal format?

I was looking at some old code in a team codebase that was doing some decimal formatting like this:

exampleDecimal.ToString("###.##")

For this example, I don't think the first 2 #'s are useful. Since all of the #'s before the . are optional digits, wouldn't this always give the same result:

exampleDecimal.ToString("#.##")

However, I read through this c# documentation, and I wasn't able to conclusively decide whether these 2 formats above were technically identical. Will they always produce the same output, or is there some case I'm missing?

Upvotes: 1

Views: 72

Answers (2)

John Wu
John Wu

Reputation: 52280

Yes, # and ## produce the same output.

However, when you use multiple # symbols, you can embed other characters. For example, a format of #,### would produce a number with commas between thousands, if it has enough digits.

Upvotes: 2

T.M.
T.M.

Reputation: 79

From your cited documentation link:

The "#" Custom Specifier The "#" custom format specifier serves as a digit-placeholder symbol. [...]

Note that this specifier never displays a zero that is not a significant digit, even if zero is the only digit in the string. It will display zero only if it is a significant digit in the number that is being displayed.

So, yes, both format strings will always produce the same results.

Upvotes: 3

Related Questions