theraneman
theraneman

Reputation: 1630

Double.ToString returns empty for 0

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

double d = 0;

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

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

Upvotes: 4

Views: 2540

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98868

From The "#" Custom Specifier

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 wanna display it as 00,000,000,000, you can use The "0" Custom Specifier instead. But remember, this specifier puts zero if it doesn't match any numeric value in your double.

That means (15).ToString("00,000,000,000") will generate 00,000,000,015 as a result.

If you want to display 0 as well other than your other values, just change your last digit format from # to 0 like ##,###,###,##0.

But a better way might be using The numeric "N" format specifier in my opinion. This specifiers generates thousands group separator and it's size, decimal separator and it's size (you can omit this part with N0) possible negative sign and it's pattern.

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

Also I want to mentioned about , in your string format. You want to group like thousands separator, (and since you don't use any IFormatProvider in your code) if your CurrentCulture's NumberGroupSeparator is different than , character, that character will be displayed, not ,.

For example; I'm in Turkey and my current culture is tr-TR and this culture has . as a NumberGroupSeparator. That's why your code will generate a result in my machine as ##.###.###.### format not ##,###,###,###.

Upvotes: 11

Emre Senturk
Emre Senturk

Reputation: 345

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

Upvotes: 0

Related Questions