Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double.ToString returns empty for 0

Tags:

c#

double

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.

like image 315
theraneman Avatar asked Oct 20 '25 22:10

theraneman


1 Answers

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 ##,###,###,###.

like image 118
Soner Gönül Avatar answered Oct 22 '25 13:10

Soner Gönül