Reputation: 523
Why is it when I'm parsing a decimal (0) ToString my string shows as empty when using the method:
String somthing = someDecimal.ToString("#")
And when I'm using:
String somthing = somDecimal.ToString("0.##")
The string shows up as 0
?
When I'm looking at the value in the debug mode in both way it's says they have a "0" in them.
Upvotes: 3
Views: 131
Reputation: 216313
If you want a fixed number of decimals after the decimal point, you need to use
String somthing = somDecimal.ToString("0.00")
In your example you use the #
specifier which means 'put here a number if there is a meaningful number'.
It would work if someDecimal
is 0.01
decimal somDecimal = 0.01m
String somthing = somDecimal.ToString("0.##");
but not if
decimal somDecimal = 0.01m
String somthing = somDecimal.ToString("0.#");
Upvotes: 2
Reputation: 460208
MSDN: the "#" Custom Specifier
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 "#" symbol appears in the format string, that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string. 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 if the decimal would be 1 instead of 0 it would be diplayed even with ToString("#")
.
Upvotes: 2
Reputation: 62276
Because pound "#" means convert to symbol if there is a number. 0
is an "empty" number, so it converts to "".
In fact, in second case, you get 0
, as you imply to show at least one digit before dot.
This all is by design convention of C# language.
Upvotes: 2
Reputation: 98810
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.
If you want to display digits after your decimal point, you need to use 0.00
instead of 0.##
.
Upvotes: 4