Double.ToString returns blank for 0

Can anyone help me understand why the "text" variable is empty for the snippet below,

double d = 0;

var text = d.ToString("##,###,###,###");

      

If I change the value of d to any non-null value, I get its correct string representation.

+3


source to share


2 answers


From "#"

Custom specifier

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

If you want to render it as 00,000,000,000

, you can use "0"

Custom Specifier
instead . But remember that this specifier puts zero if it doesn't match any numeric value in your double.

This means it (15).ToString("00,000,000,000")

will generate 00,000,000,015

.

If you want to display 0

, and not your other values, just change the format of the last digit from #

to 0

, like ##,###,###,##0

.



But the best way might be to use a Numeric format specifier"N"

in my opinion. These specifiers generate thousands of group separators and size, decimal separator and its size (you can omit this part with N0

) possible negative sign and its pattern.

double d = 0;
var text = d.ToString("N0");

      

Also I want to mention about ,

in your string format. You want to group as a thousand separator (and since you are not using IFormatProvider

in your code), if yours is different from a character , that character will be, not .CurrentCulture

NumberGroupSeparator

,

,

For example; I am in Turkey, and my current culture tr-TR

, and this culture has .

both NumberGroupSeparator

. Therefore your code will generate the result on my machine in ##.###.###.###

not format ##,###,###,###

.

+10


source


For string formatting, # is an optional place. For example, a format string such as "# 0" displays the first numeric character if the number is equal to or greater than 10. Therefore, you need to convert your hashtags to zero if you want to display your number.



0


source