Why does 0.ToString("#.##") return an empty string instead of 0.00 or at least 0?
Why does 0.ToString("#.##")
return an empty string? Shouldn't it be 0.00
or at least 0?
#
in the string format indicate that the value is optional. If you wish to get the output 0.00
you need the following:
0.ToString("0.00");
See here for the custom numeric formats that can be passed to this method.
Because in a format string, the #
is used to signify an optional character placeholder; it's only used if needed to represent the number.
If you do this instead: 0.ToString("0.##");
you get: 0
Interestingly, if you do this: 0.ToString("#.0#");
you get: .0
If you want all three digits: 0.ToString("0.00");
produces: 0.00
From the comments to this answer, your argument seems to be,
it should show '0', because why would anyone ever want to see an empty string if the numeric value is 0?
The response is simple: You have the choice how you wish it to be displayed. That's what the custom format strings are for. You have simply chosen the incorrect format string for your needs.
According to the documentation about the Digit Placeholder.
If the value being formatted has a digit in the position where the '#' appears in the format string, then that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string. This specifier never displays the '0' character if it is not a significant digit, even if '0' is the only digit in the string. It will display the '0' character if it is a significant digit in the number being displayed. The "##" format string causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "##" would result in the value 35.
If you want the zero to display use the Zero PlaceHolder
f the value being formatted has a digit in the position where the '0' appears in the format string, then that digit is copied to the result string. The position of the leftmost '0' before the decimal point and the rightmost '0' after the decimal point determines the range of digits that are always present in the result string.
The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.